How to move all negative elements to the beginning of array in Node.js

1 Answer

0 votes
function move_negative_to_beginning(arr) {
    let beginning_index = 0;
    
    const size = arr.length;
    
    for (let i = 0; i < size; i++) {
        if (arr[i] < 0) {
            
            [arr[i], arr[beginning_index]] = [arr[beginning_index], arr[i]];

            beginning_index++;
        }
    }
}
        
const arr = [-1, 8, -6, 21, -3, 4, -2, 0, 15, -30, -40, 9, -5];

move_negative_to_beginning(arr);

console.log(arr);


  
  
  
/*
run:
  
[
  -1, -6, -3, -2, -30, -40,
  -5,  0, 15,  8,   4,   9,
  21
]
  
*/

 



answered Aug 22, 2022 by avibootz

Related questions

...