How to find first and last positions of an element in a sorted array in JavaScript

1 Answer

0 votes
function find_first_and_Last_position(arr, n) { 
    let first = -1;
    let last = -1; 
      
    for (let i = 0; i < arr.length; i++) { 
        if (n != arr[i]) 
            continue; 
        if (first == -1) 
            first = i; 
        last = i; 
    } 
 
    return [first, last];
} 

 
const arr = [1, 3, 7, 8, 3, 1, 9]; 
const n = 3; 
      
const result = find_first_and_Last_position(arr, n); 
  
const first = result[0];
const last = result[1];
  
if (first != -1) {
    console.log("First positions = " + first + " Last positions = " + last); 
}
else {
    console.log("Not found\n"); 
}

 
/*
run:
 
First positions = 1 Last positions = 4
 
*/

 



answered Aug 9, 2019 by avibootz
edited May 9 by avibootz
...