This context explains how to sort an array of numbers numerically in JavaScript using the sort() method and a comparison function.
Abstract
The context begins by explaining the default behavior of the sort() method in JavaScript, which sorts elements in an array in lexicographical (alphabetical) order, not numerical order. This means that when sorting an array of numbers, the sort() method will not produce the expected result. To achieve a numerical sort, a comparison function must be passed to the sort() method as a parameter. The comparison function should return a negative value if the first item is smaller, a positive value if the first item is larger, and 0 for equality. The context provides examples of how to use the comparison function to sort an array of numbers in both ascending and descending order. It also explains how to protect the original array from being modified by the sort() method by using the slice() method, the spread operator, or the Object.assign() method.
Bullet points
The sort() method in JavaScript sorts elements in an array in lexicographical order by default.
To achieve a numerical sort, a comparison function must be passed to the sort() method as a parameter.
The comparison function should return a negative value if the first item is smaller, a positive value if the first item is larger, and 0 for equality.
Examples of how to use the comparison function to sort an array of numbers in both ascending and descending order are provided.
The slice() method, the spread operator, or the Object.assign() method can be used to protect the original array from being modified by the sort() method.
How to sort an array numerically in JavaScript
The default ECMAScript sort is alphabetical, so a little magic is needed to sort an array in numerical order.
To sort the array numerically in ascending order, That comparison function should return the difference between the two numbers.
This is achieved by subtracting the second item from the first.
That’s more like it!
The (a,b)=>a-b comparison function subtracts the second item from the first item, thus returning a negative value if the second item is bigger, a positive value if the second item is smaller, and 0 for equality.