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. [GFGTABS] JavaScript let arr = [[3, 2], [1, 4], [2, 5], [2, 0]]; arr.sort(); console.log(arr); [/GFGT
2 min read
Reverse an Array in JavaScript
Here are the different methods to reverse an array in JavaScript 1. Using the reverse() MethodJavaScript provides a built-in array method called reverse() that reverses the elements of the array in place. This method mutates the original array and returns the reversed array. [GFGTABS] JavaScript let
3 min read
Sort an array of Strings in JavaScript ?
Here are the various methods to sort an array of strings in JavaScript 1. 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. [GFGTABS] JavaScript let a
3 min read
Sort an array in reverse order JavaScript
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() m
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
Sort an Object Array by Date in JavaScript
To sort an Object Array by Date in JavaScript, we have different approaches. We are going to learn how to sort an Object Array by Date in JavaScript. Below are the approaches to sort an Object Array by Date in JavaScript: Table of Content Using sort method with Date objectsUsing sort() method with g
4 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 Strings[GFGTABS] JavaScript // Original array let ar = ["JS", "HTML", "CSS"]; console.log(
4 min read
How to Filter an Array in JavaScript ?
The array.filter() method is used to filter array in JavaScript. The filter() method iterates and check every element for the given condition and returns a new array with the filtered output. Syntax const filteredArray = array.filter( callbackFunction ( element [, index [, array]])[, thisArg]);Note:
2 min read
JavaScript â Min Element in an Array
These are the following ways to find the minimum element in JS array: Note: You must add a conditional check for checking whether the given array is empty or not, if the array is not empty then you can use the given below approaches to find out the minimum element among them. 1. Using Math.min() Met
3 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. [GFGTABS] JavaScript let s1 = "javascript
2 min read