0

When using the sort method in JavaScript, it doesn't give me the right result. What could be the reason for this? Code below and its output:

let numbers = [14, -124, 68, 2, 56, -111, 0, 69, 9];
numbers.sort();
console.log(numbers);

Output: [-111, -124, 0, 14, 2, 56, 68, 69, 9]

1 Answers1

1
let numbers = [14, -124, 68, 2, 56, -111, 0, 69, 9];
numbers = numbers.sort((a, b) => a - b);
console.log(numbers);

->

[
  -124, -111,  0,  2,
     9,   14, 56, 68,
    69
]

The default sorting is alphabetical unfortunately

Gab
  • 3,404
  • 1
  • 11
  • 22
  • Please don't answer obvious duplicates, especially ones that have comments on them saying "Does this answer your question?" followed by a link to a duplicate question. – Heretic Monkey Jan 26 '21 at 15:52
  • "This question already has answers here" was not there at the time I was writing my answer – Gab Jan 26 '21 at 16:00
  • comments on them saying "Does this answer your question?" followed by a link to a duplicate question. – Heretic Monkey Jan 26 '21 at 16:11