Search code snippets, questions, articles...

Sort array using Array.sort() in javascript

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

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' }
fruits.sort(function (a, b) { return });
Best JSON Validator, JSON Tree Viewer, JSON Beautifier at same place.

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?

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 - });