-3

If array A = [-1, -3, -2, 0];

if I try to sort it like A.sort()

console.log(A)

return is [-1, -2, -3, 0] instead of [-3, -2, -1, 0]

ThS
  • 4,597
  • 2
  • 15
  • 27
Error404
  • 3
  • 1
  • 2
    [The default sort converts the items into strings.](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort) You can write your own. (`A.sort((a,b) => a>b)` for instance) – evolutionxbox Oct 06 '22 at 09:06
  • 1
    [Array.prototype.sort()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort) - "The default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values." – Ben Fortune Oct 06 '22 at 09:06

2 Answers2

0

The Array.prototype.sort accepts an optional callback function (a compare function) that you use to sort the array based on your preference.
In your example above, you didn't specify a compare function thus sort will default to:

sorting the elements of an array in place and returns the reference to the same array, now sorted. The default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values. Source: MDN

From the result sample you included, it seems you want to sort those numbers in an ascending order (smaller to bigger). To do so, you should pass a compare function to the sort method that describes that sorting logic you'd want to have.

Here's a live demo:

const myArray = [-1, -3, -2, 0];

/** Please check the linked docs page for more details */
console.log(myArray.sort((a, b) => a < b ? -1 : 1)); // or simply: "(a, b) => a - b)"

The above demo should print: [-3, -2, -1, 0].

ThS
  • 4,597
  • 2
  • 15
  • 27
-1

You can do this: A.sort((a, b) => a-b);

B.Wesselink
  • 63
  • 12