JavaScript – Sort a Numeric Array
Here are some common methods to Sort Numeric Array using JavaScript. Please note that the sort function by default considers number arrays same as an array of stings and sort by considering digits as characters.
Using sort() with a Comparison Function – Most Used
The sort() method in JavaScript, when used with a comparison function, can sort the numeric arrays in ascending or descending order. This is the most frequently used approach.
const a = [5, 2, 9, 1, 7];
// Ascending order
a.sort((x, y) => x - y);
console.log(a);
// Descending order
a.sort((x, y) => y - x);
console.log(a);
Sorting According to Absolute Value
Using the sort() method with a function allows you to define a custom comparison, like sorting based on absolute values or custom criteria. This is useful when you want to sort by specific criteria beyond ascending or descending order.
const a = [-3, 7, -1, 5];
// Sort by absolute values
a.sort((x, y) => Math.abs(x) - Math.abs(y));
console.log(a);
Using Intl.Collator for Locale-Specific Sorting
Intl.Collator is mainly used for strings, but it can be used for sorting mixed or number-as-string arrays. However, for pure numeric arrays, this is generally not recommended.
const a = [10, 1, 5, 20];
const collator = new Intl.Collator('en', { numeric: true });
a.sort(collator.compare);
console.log(a);
Output
[1, 5, 10, 20]
Importance of Sorting Numeric Arrays
Sorting numeric arrays is essential for
- Data Analysis: Enables ranking, grouping, and trend analysis.
- Optimized Searching: Sorted data allows for faster search algorithms, like binary search.
- Data Presentation: Displays data in a logical and structured way, enhancing readability.