Chrome Extension

Sort array using Array.sort() in javascript

Array.sort() method can be used to sort an array in ascending and descending order.
//SORT ARRAY ALPHABETICALLY
var arr = ["Joe", "Victor", "Henna"];
arr.sort();
arr.reverse(); //DESCENDING ORDER

//SORT ARRAY NUMERICALLY
var numeric_arr = [50, 20, 40, 60, 10, 30];
numeric_arr.sort(function(a, b) { return a - b }); //ASCENDING ORDER
numeric_arr.sort(function(a, b) { return b - a }); //DESCENDING ORDER

//Array of Objects
var fruits = [
    { 'name': 'banana', 'color': 'yellow' },
    { 'name': 'apple', 'color': 'red' },
    { 'name': 'orange', 'color': 'orange' }
];
//SORT ARRAY OF OBJECT
fruits.sort(function (a, b) { return a.name.localeCompare(b.name) });
console.log(fruits);
Best JSON Validator, JSON Tree Viewer, JSON Beautifier at same place. Check how cool is the tool

You can sort an array in javascript using .sort() function. If you want to sort it alphabetically, you just need to add function .sort() after the variable which you have assigned the array. For numeric sort, you need to pass a function inside .sort().

If we have sorted array alphabatically using Array.sort() function then it will sort it in ascending order to make it sort in descending order you will have to use Array.reverse() method.

If you have an array of objects and the object has particular keys and values pairs. Id you want to sort them using a key value pair then you can use .localeCompare() method and compare two values.

A working demo for sorting array values can be found below:

Was this helpful?
1 Comments

If you want to sort array of objects on the basis of key value

var arr = [
    {"id": 3, "name": "Joe"},
    {"id": 1, "name": "Victor"},
    {"id": 2, "name": "Henna"}
];


arr.sort(function(a, b) { return a.id - b.id });
Join Devsheet Ask a Question