Sort an Array in JavaScript
Last Updated :
14 Nov, 2024
This article will show you how to sort a JS array.
1. Using array.sort() Method
To sort an array in JavaScript, we can use array.sort() method. This method sorts the elements alphabetically in ascending order.
JavaScript
let arr = ["JS", "HTML", "CSS"];
arr.sort()
console.log(arr);
Output[ 'CSS', 'HTML', 'JS' ]
Please refer to the JavaScript Array Tutorial for a comprehensive understanding of JavaScript Arrays.
Using Comparator function
Sorting a numeric array involves using a coparator funtion with the JS array.sort() method.
JavaScript
const arr = [ 10, 20, 25, 100 , 40]
console.log(arr.sort((a,b) => a - b))
Output[ 10, 20, 25, 40, 100 ]
Please go through this How to Sort Numeric Array using JavaScript?, to know how the javascript array sort function works.
Using Custom Functions
Sorting the complex arrays (e.g., array of objects ) with custom functions based on the object property.
JavaScript
// Array of people objects with different names and ages
let arr = [
{ name: 'Rahul', age: 28 },
{ name: 'Jatin', age: 25 },
{ name: 'Vikas', age: 32 },
{ name: 'Rohit', age: 35 }
];
// Custom comparision function for object property
arr.sort((a, b) => a.age - b.age);
console.log(arr);
// Sort object for names
arr.sort((a, b) => a.name.localeCompare(b.name));
console.log(arr);
Output[
{ name: 'Jatin', age: 25 },
{ name: 'Rahul', age: 28 },
{ name: 'Vikas', age: 32 },
{ name: 'Rohit', age: 35 }
]
[
{ name: 'Jatin', age: 25 },
{ name: 'Rahul', age: 28 },
{ name: 'Rohi...
2. Using array.toSorted() Method
JS array.toSorted() works same as the array.sort() method but it creates a new array instead of updating the existing array.
Sorting Array of Strings
JavaScript
const a = ["JS", "HTML", "CSS"];
const a1 = a.toSorted();
console.log(a);
console.log(a1);
Output
[ 'JS', 'HTML', 'CSS' ]
[ 'CSS', 'HTML', 'JS' ]
Using Comparator Function
To sort the numeric array propery we have to pass a comparator function.
JavaScript
const arr = [ 10, 20, 25, 100 , 40]
console.log(arr.toSorted((a,b) => a - b))
Output
[ 10, 20, 25, 40, 100 ]
We can also use the algorithms for sorting like bubble sort, insertion sort etc. Check this article, Sorting Algorithms in JS, to learn more about the sorting algorithms in JavaScript.
3. Sort JS Array in Reverse Order
Change the comparator function to reverse the output
JavaScript
const arr = [ 10, 20, 25, 100 , 40]
console.log(arr.sort((a,b) => b - a))
Output[ 100, 40, 25, 20, 10 ]
We can also use Array.reverse() method to sort the JS array in Descending Order
JavaScript
let arr = ["JS", "CSS", "HTML"];
// Sorting the array
arr.sort();
arr.reverse();
console.log(arr);
Output[ 'JS', 'HTML', 'CSS' ]
Sorting Stability in JS array sort()
Sort stability refers a sorting algorithm preserves the relative order of elements that have equal values. A sorting algorithm is stable if, when two or more items have the same value, they remain in the same relative order after sorting.
Please go through this, is Array sort stable, to know more about the sort stability.
The ES2019 update mandates that JavaScript's Array.prototype.sort() method uses a stable sorting algorithm, ensuring equal elements maintain their original order across all major JavaScript engines.
JavaScript
const arr = [
{ name: "Aman", marks: 80 },
{ name: "Rajat", marks: 85 },
{ name: "Rishabh", marks: 82 },
{ name: "Amit", marks: 80 }
];
arr.sort((a, b) => a.marks - b.marks);
console.log(arr);
Output[
{ name: 'Aman', marks: 80 },
{ name: 'Amit', marks: 80 },
{ name: 'Rishabh', marks: 82 },
{ name: 'Rajat', marks: 85 }
]
We have a complete list of Javascript Array methods, to check those please go through this Javascript Array Complete reference article.
Similar Reads
Sort An Array Of Arrays In JavaScript The following approaches can be used to sort array of arrays in JavaScript.1. Using array.sort() Method- Mostly UsedJS array.sort() is used to sort and update the original array in ascending order.JavaScriptlet arr = [[3, 2], [1, 4], [2, 5], [2, 0]]; arr.sort(); console.log(arr);Output[ [ 1, 4 ], [
2 min read
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 UsedThe sort() method in JavaScript, when
2 min read
Is JavaScript Array Sort Stable ? Javascript Array Sort is stable: As of version 10 (or ECMAScript 2019), the specification requires Array.prototype.sort to be stable. In javascript, stable sorting is if an array objects with (key, value) pair has equal keys appear in the same order in sorted output as they appear in the input data
3 min read
JavaScript - Sort an Array of Strings Here are the various methods to sort an array of strings in JavaScript1. Using Array.sort() MethodThe sort() method is the most widely used method in JavaScript to sort arrays. By default, it sorts the strings in lexicographical (dictionary) order based on Unicode values.JavaScriptlet a = ['Banana',
3 min read
JavaScript Array sort() Method The JS array.sort() method rearranges the array elements alphabetically and returns a sorted array. It does not create a new array but updates the original array.Sorting Array of StringsJavaScript// Original array let ar = ["JS", "HTML", "CSS"]; console.log(ar); // Sorting the array ar.sort() consol
4 min read
Sort a String in JavaScript Here are the most used methods to sort characters in a string using JavaScript.Using split(), sort(), and join()The most simple way to sort a string is to first convert it to an array of characters, sort the array, and then join it back into a string.JavaScriptlet s1 = "javascript"; let s2 = s1.spli
2 min read
JavaScript - Sort an Array in Reverse Order in JS JS array.sort() Method sorts the array in ascending order. We can make it descending or reverse order using array.reverse() method. Below are the following ways to sort an array in reverse order:1. Using array.sort() with array.reverse()First, sort the given array of strings using JS array.sort() me
2 min read
Sort Mixed Alpha/Numeric array in JavaScript Sorting a mixed alpha/numeric array in JavaScript involves arranging the elements in a specified order, typically lexicographically (dictionary order) for strings and numerically for numbers. When these types are mixed, a custom sort function is required to effectively handle comparisons between dif
3 min read
How to sort a set in JavaScript ? Sorting a Set based on the values of its elements is a common need in JavaScript. While the built-in sort() function can't be directly applied to a Set, there's a workaround. Let's explore how we can achieve this: Instead of directly sorting the Set, we'll: Convert the Set into an array to make it s
3 min read
Javascript Program to Sort an array in wave form Given an unsorted array of integers, sort the array into a wave like array. An array 'arr[0..n-1]' is sorted in wave form if arr[0] >= arr[1] <= arr[2] >= arr[3] <= arr[4] >= .....Examples: Input: arr[] = {10, 5, 6, 3, 2, 20, 100, 80} Output: arr[] = {10, 5, 6, 2, 20, 3, 100, 80} OR {
4 min read