How to sort an array of objects in JavaScript?

We have a lot of algorithms to sort lists or arrays in JavaScript. Sorting an array is quite straightforward. Many developers don’t bother about the algorithms and just use the JavaScript sort method.

When it comes to sorting an array of objects in JavaScript then it becomes a little tricky. We may need to sort based on the numeric field of an object or a string field. Following is the code with an example:

    const statePriceList = [
        {
            "city": "Dallas",
            "state": "TX",
            "zip": "75201",
            "price": 105
        },
        {
            "city": "Bevery Hills",
            "state": "CA",
            "zip": "90210",
            "price": 99
        },
        {
            "city": "Sacramento",
            "state": "CA",
            "zip": "94203",
            "price": 100
        },
        {
            "city": "New York",
            "state": "NY",
            "zip": "00010",
            "price": 70
        }
    ];

How to sort based on numeric field?

statePriceList.sort((a, b) => parseFloat(b.price) - parseFloat(a.price)); // Descending order
console.log(statePriceList);


statePriceList.sort((a, b) => parseFloat(a.price) - parseFloat(b.price)); // Ascending order
console.log(statePriceList);

How to sort based on string field?

statePriceList.sort((a, b) => a.city.localeCompare(b.city)); // localeCompare() is case insensitive
console.log(statePriceList);
Share