How to find the starting and ending position of a given value in an integer array in Node.js

1 Answer

0 votes
function findStartingEndingPosition(arr, value) {
    let result = Array(2).fill(-1);
  
    for (let i = 0; i < arr.length; i++) {
        if (arr[i] !== value) {
            continue;
        }
  
        if (result[0] === -1) {
            result[0] = i;
        }
          
        result[1] = i;
    }
  
    return result;
}
          
const arr = [1, 3, 2, 4, 9, 7, 7, 8, 8, 8, 10, 11, 8, 8, 17];
const value = 8;
  
const result = findStartingEndingPosition(arr, value);
  
console.log("start: " + result[0]);
console.log("end: " + result[1]);
  
  
  
/*
run:
  
start: 7
end: 13
  
*/

 



answered Mar 31, 2024 by avibootz
...