How to Sort an Array of Objects in Javascript

javascript
Published on September 24, 2019

Use-Cases of this Tutorial

  • Sort an array containing objects alphabetically by some key-value.
  • Sort an array containing objects by date.
  • Sort an array containing objects by number.

This tutorial explains how to perform advanced sorting on an array of objects with native Javascript methods.

Concepts and Methods Involved

  • sort()

    The sort method can be used to sort an array. If the array contains objects as elements, then a custom sorting callback function can be specified to sort using key(s) of the included objects. This callback is specified as a parameter to sort().

    // array to sort
    var arr = [ {name: "Lewis", team: "Mercedes"}, {name: "Charles", team: "Ferrari"} ];
    
    // sort array with a custom function
    arr.sort(function(first_el, second_el) {
        // custom sorting code
    });
    
    // final sorted array
    console.log(arr);
    

    Sorting an array is obviously comparing 2 elements at one time, and repeating this for all elements in the array. When sort() tries to compare 2 elements, the custom callback is invoked and the 2 elements being compared are passed as parameters to this callback. The return value of the callback can be greater than 0, less than 0 or 0. According to these return values, the sorted positions of the two elements are set :

    • If return value is less than 0, then first element comes before the second element.
    • If return value is greater then 0, then second element comes before the first element.
    • If return value is 0, then positions of first and second element is left unchanged with respect to each other.
    // sample sorting function that compares numbers
    function compare(first_el, second_el) {
        if(first_el < second_el)
            return -1;
        else if(first_el > second_el)
            return 1;
        else if(first_el == second_el)
            return 0;
    });
    

    Return value of sort() : The final sorted array is returned. sort() is mutable and the initial array is changed as well.

  • localeCompare()

    Comparing 2 numbers is direct through comparison operators, but sometimes we need to compare 2 strings as to which one comes earlier. In such cases localeCompare() can be used to compare two strings alphabetically. localeCompare() is pretty powerful and can even compare strings of different languages.

    var a = 'Ferrari';
    var b = 'Mercedes';
    
    if(a.localeCompare(b) < 0)
        console.log('"Ferrari" comes before "Mercedes"');
    else if(a.localeCompare(b) > 0)
        console.log('"Ferrari" comes after "Mercedes"');
    else if(a.localeCompare(b) == 0)
        console.log('Both strings equal');
    
    // "Ferrari" comes before "Mercedes"
    

    Return Value of localeCompare() :

    • A negative integer value is returned if main string comes before the comparison string.
    • A positive integer value is returned if main string comes after the comparison string.
    • 0 is returned if main string is same as comparison string.

Example #1 — Sorting Alphabetically by Key

The below array is sorted using a custom sorting function — in this case array is sorted alphabetically on the key "team".

var arr = [ {name: "Lewis", team: "Mercedes AMG F1"}, 
    {name: "Charles", team: "Scuderia Ferrari"}, 
    {name: "Valtteri", team: "Mercedes AMG F1"}, 
    {name: "Max", team: "Redbull Racing"}, 
    {name: "Sebastian", team: "Scuderia Ferrari"}, 
    {name: "Alex", team: "Redbull Racing"}
];

arr.sort(function(first_el, second_el) {
    // selecting key to sort
    var fname = first_el.team;  
    var sname = second_el.team;

    if(fname.localeCompare(sname) < 0)
        return -1;
    else if(fname.localeCompare(sname) > 0)
        return 1;
    else if(fname.localeCompare(sname) == 0)
        return 0;
});

console.log(arr);

// { name: "Lewis", team: "Mercedes AMG F1" }
​// { name: "Valtteri", team: "Mercedes AMG F1" }
​// { name: "Max", team: "Redbull Racing" }
​// { name: "Alex", team: "Redbull Racing" }
​// { name: "Charles", team: "Scuderia Ferrari" }
​// { name: "Sebastian", team: "Scuderia Ferrari" }

If we need to implement a reverse sort then this can simply be done by just changing the return value.

arr.sort(function(first_el, second_el) {
    var fname = first_el.team;  
    var sname = second_el.team;

    if(fname.localeCompare(sname) < 0)
        return 1;
    else if(fname.localeCompare(sname) > 0)
        return -1;
    else if(fname.localeCompare(sname) == 0)
        return 0;
});

Example #2 — Sorting by Number

var arr = [ {name: "Vettel", standing: 5}, 
    {name: "Leclerc", standing: 3}, 
    {name: "Bottas", standing: 2}, 
    {name: "Hamilton", standing: 1}, 
    {name: "Verstappen", standing: 4}
];

// sort in acsending order by "standing" key
arr.sort(function(first, second) {
    var frank = first.standing;
    var srank = second.standing;

    if(frank > srank)
        return 1;

    if(frank < srank)
        return -1;

    return 0;
});

console.log(arr);

// { name: "Hamilton", standing: 1 }
​// { name: "Bottas", standing: 2 }
​// { name: "Leclerc", standing: 3 }
​// { name: "Verstappen", standing: 4 }
​// { name: "Vettel", standing: 5 }

Example #3 — Sorting by Date

If the objects contains a date string, it can be converted to a Javascript Date object. Then comparsion operations can be used to sort them accordingly.

var arr = [ {name: "Bottas", dob: "1989-08-28"}, 
    {name: "Leclerc", dob: "1997-10-16"}, 
    {name: "Vettel", dob: "1987-07-03"}, 
    {name: "Verstappen", dob: "1997-09-30"}, 
    {name: "Hamilton", dob: "1985-01-07"}
];

// sort in decsending order by "dob" key
arr.sort(function(first, second) {
    // convert date string to Date object
    var fts = new Date(first.dob);
    var sts = new Date(second.dob);

    if(fts > sts)
        return -1;

    if(fts < sts)
        return 1;

    return 0;
});

console.log(arr);

// { name: "Leclerc", dob: "1997-10-16" }
​// { name: "Verstappen", dob: "1997-09-30" }
​// { name: "Bottas", dob: "1989-08-28" }
​// { name: "Vettel", dob: "1987-07-03" }
​// { name: "Hamilton", dob: "1985-01-07" }

Useful Resources

  • Array.sort() — API documentation for sort().
  • String.localeCompare() — API documentation for localeCompare().
    localeCompare() includes a lot of other options like setting the language of the strings, ignoring punctuations, locale matching algorithm etc. Setting these options can be useful for comparing non-english strings.
In this Tutorial