-2

Array.sort() function isn't returning expected result. Is that how it actualy works, or what?

const arr = [1, 5, 12, 8, 17];
console.log(arr.sort());

Expected result would be: [1, 5, 8, 12, 17] but result I get is: [1, 12, 17, 5, 8]

Asca Fasd
  • 3
  • 1

1 Answers1

1

You need to pass a callback to sort array of integers. If you don't pass a callback by default it will sort according to UTF-16 code value units. According to MDN

The sort() method sorts the elements of an array in place and returns the sorted array. The default sort order is built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values

const arr = [1, 5, 12, 8, 17];
console.log(arr.sort((a,b) => a - b));
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73