0

In my example firstArr, the .sort() method works properly, but when I try .sort() on secondArr, which has values over 1000, it breaks. Why is this? I have tried to find documentation on .sort() and it's limits, but i've come up short. Thank you.

var firstArr = [ 1 , 10, 5, 15];
firstArr.sort();    // [1, 5, 10, 15];

var secondArr = [1000, 500, 999, 150];
secondArr.sort();    //[1000, 150, 500, 999];

1 Answers1

0

You must provide a compareFunction for it to work.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

arr = [1, 2, 3, 4];
function ascent(a, b) {
  return a - b;
}
function descent(a, b) {
  return b - a;
}
arr.sort(ascent);
console.log(arr);
arr.sort(descent);
console.log(arr);
Cuong Vu
  • 3,423
  • 14
  • 16