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]
CodePudding user response:
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));
The above demo should print: [-3, -2, -1, 0]
.
CodePudding user response:
You can do this: A.sort((a, b) => a-b);