![]() |
VOOZH | about |
This article will show you how to sort a JS array.
To sort an array in JavaScript, we can use array.sort() method. This method sorts the elements alphabetically in ascending order.
[ '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.
[ 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.
[
{ 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...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
Output
[ 'JS', 'HTML', 'CSS' ]
[ 'CSS', 'HTML', 'JS' ]
Using Comparator Function
To sort the numeric array propery we have to pass a comparator function.
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.
Change the comparator function to reverse the output
[ 100, 40, 25, 20, 10 ]
We can also use Array.reverse() method to sort the JS array in Descending Order
[ 'JS', 'HTML', 'CSS' ]
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.
[
{ 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.