A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/javascript/how-to-sort-numeric-array-using-javascript/ below:

JavaScript - Sort a Numeric Array

JavaScript - Sort a Numeric Array

Last Updated : 12 Jul, 2025

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.

JavaScript
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.

JavaScript
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.

JavaScript
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



RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4