How to sort an array of integers in Node.js

1 Answer

0 votes
let arr = [4, 1, 20, -5, 12, -9, 7, 6];
 
arr.sort(function(a, b) {
    if (a === Infinity ) 
        return 1; 
    else if (isNaN(a)) 
        return -1;
    else
        return a - b;
});
 
console.log(arr);
 
 
 
 
/*
run:
 
[
  -9, -5,  1,  4,
   6,  7, 12, 20
]
 
*/

 

 



answered Sep 2, 2022 by avibootz
...