terça-feira, 2 de janeiro de 2024

Sorting an int array in JavaScript

First we create a descendant array from 1000 to 1:

let arr = Array.from({length: 1001}, (_, i) => 1001 - i);
Then we sort it:

arr = arr.sort();
console.log(arr);
and we get the following:

(1001) [1, 10, 100, 1000, 1001, 101, 102, 1…]
That happens because JavaScript sorts each position as it were a String. To fix that we can pass the sorting function. It works similar to C or Java, the sorting function must return: 
  •  = 0 if a and b are equal 
  • < 0 if a < b 
  • > 0 if a > b

arr = arr.sort((a, b) => a - b);
console.log(arr);

Nenhum comentário: