How To Sort Array Of Objects By String Property Value – Definitive Guide

Sorting in JavaScript is a process of arranging objects in order sequentially or by grouping objects.

In JavaScript, You can use arr.sort((a, b) => a.propertyName - b.propertyName ) syntax to sort array of objects by string property value.

The JavaScript object can be sorted using the property key, given to compare function to evaluate the value to identify the order.

Sort by property Ascending(Quick Solution)

The sort() method with compare function, helps to arrange array elements in an order.

Sort by Property with String value Ascending

This example shows the behavior of sorting a property with a string value in Ascending order.

So basically, the sorting happens based on the return value of the sort function after comparison,

  • if a negative value is returned, then the order is changed.
  • if a positive value is returned, the order remains the same.

Code

    let students = [{
            firstName: 'Jessica',
            lastName: 'Jones',
            dateOfBirth: 'March 15, 2008',
            age: 14
        },
        {
            firstName: 'Sachin',
            lastName: 'Lara',
            dateOfBirth: 'April 20, 2007',
            age: 15
        },
        {
            firstName: 'Mohammad',
            lastName: 'Ali',
            dateOfBirth: 'Spetember 11, 2008',
            age: 13
        }
    ];

    function compare(a, b) {
        if (a.firstName < b.firstName) {
            return -1;
        }
        if (a.firstName > b.firstName) {
            return 1;
        }
        return 0;
    }

    students.sort(compare);

    //below code is to print the value
    students.forEach((student) => {
        console.log(`${student.firstName} ${student.lastName} ${student.age}`);
    });

Output

    "Jessica Jones 14"
    "Mohammad Ali 13"
    "Sachin Lara 15"

The sorting took place based on the firstName property, as it was used in the compare function to sort the JavaScript object

Sort by Property with Number value Ascending

let us see an example to sort array of objects based on a property with a number value using the ES6 arrow function.

Code

    let students = [{
            firstName: 'Jessica',
            lastName: 'Jones',
            dateOfBirth: 'March 15, 2008',
            age: 14
        },
        {
            firstName: 'Sachin',
            lastName: 'Lara',
            dateOfBirth: 'April 20, 2007',
            age: 15
        },
        {
            firstName: 'Mohammad',
            lastName: 'Ali',
            dateOfBirth: 'Spetember 11, 2008',
            age: 13
        }
    ];

    students.sort((a, b) => a.age - b.age);

    //below code is to print the value
    students.forEach((student) => {
        console.log(`${student.firstName} ${student.lastName} ${student.age}`);
    });

Output

    "Mohammad Ali 13"
    "Jessica Jones 14"
    "Sachin Lara 15"

The above example uses the property(age) as a sort parameter.

Each array element is iterated, and the current age value is compared with the following age value to sort array of objects.

Sort by property Descending

You have to swap the property used in ascending sort condition to sort array of objects in a reverse order(descending).

Sort by Property with String value Descending

Let us see an example demonstrating the descending sorting for a property with a String value.

Code

    let students = [{
            firstName: 'Jessica',
            lastName: 'Jones',
            dateOfBirth: 'March 15, 2008',
            age: 14
        },
        {
            firstName: 'Sachin',
            lastName: 'Lara',
            dateOfBirth: 'April 20, 2007',
            age: 15
        },
        {
            firstName: 'Mohammad',
            lastName: 'Ali',
            dateOfBirth: 'Spetember 11, 2008',
            age: 13
        }
    ];

    students.sort((a, b) => a.firstName < b.firstName ? 1 : -1);

    students.forEach((student) => {
        console.log(`${student.firstName} ${student.lastName} ${student.age}`);
    });

Output

    "Sachin Lara 15"
    "Mohammad Ali 13"
    "Jessica Jones 14"

Here, You can see the objects are arranged to descend and printed.

Sort by Property with Number value Descending

The below example demonstrates to sort array of objects with the JavaScript object property having a numerical value in descending order.

Code

    let students = [{
            firstName: 'Jessica',
            lastName: 'Jones',
            dateOfBirth: 'March 15, 2008',
            age: 14
        },
        {
            firstName: 'Sachin',
            lastName: 'Lara',
            dateOfBirth: 'April 20, 2007',
            age: 15
        },
        {
            firstName: 'Mohammad',
            lastName: 'Ali',
            dateOfBirth: 'Spetember 11, 2008',
            age: 13
        }
    ];

    students.sort((a, b) => b.age - a.age);

    //below code is to print the value
    students.forEach((student) => {
        console.log(`${student.firstName} ${student.lastName} ${student.age}`);
    });

Output

    "Sachin Lara 15"
    "Jessica Jones 14"
    "Mohammad Ali 13"

The above example is a straight swap of the ascending function by comparing the second value against the first value to sort array of objects in descending order.

Sort-Object with Dynamic Properties

When you work with large datasets, you may require dynamic sorting based on different property fields in different situations. So the below code will help you to have a single method to achieve sorting with code reusability.

Code

    let students = [{
            firstName: 'Jessica',
            lastName: 'Jones',
            dateOfBirth: 'March 15, 2008',
            age: 14
        },
        {
            firstName: 'Sachin',
            lastName: 'Lara',
            dateOfBirth: 'April 20, 2007',
            age: 15
        },
        {
            firstName: 'Mohammad',
            lastName: 'Ali',
            dateOfBirth: 'Spetember 11, 2008',
            age: 13
        }
    ];    

    function generateSortFn(prop, desc) {
        return function(a, b) {
            if (a[prop] < b[prop]) return desc ? 1 : -1;
            if (a[prop] > b[prop]) return desc ? -1 : 1;
            return 0;
        };
    }

    students.sort(generateSortFn('age', false));

    //below code is just to print the value
    students.forEach((student) => {
        console.log(`${student.firstName} ${student.lastName} ${student.age}`);
    });

    students.sort(generateSortFn('firstName', true));

    //below code is to print the value
    students.forEach((student) => {
        console.log(`${student.firstName} ${student.lastName} ${student.age}`);
    });

Output

    //sort based on the age ascending
    "Mohammad Ali 13"
    "Jessica Jones 14"
    "Sachin Lara 15"

    //sort based on firstName descending
    "Sachin Lara 15"
    "Mohammad Ali 13"
    "Jessica Jones 14"

Sort by array.sort()

Simple use of arr.sort() will help you to sort the array of values in JavaScript, and arr.reverse() will sort the array of values in reverse order.

Code

    const data = ['Orange', 'Ball', 'Sun', 'Apple', 10, 3, 22, 34, 66, 1];

    data.sort();
    console.log(data);

    data.reverse();
    console.log(data);

Output

    [1, 10, 22, 3, 34, 66, "Apple", "Ball", "Orange", "Sun"]

    ["Sun", "Orange", "Ball", "Apple", 66, 34, 3, 22, 10, 1]

Sort in Random Order

The below logic can be used in cases when you want to make a random sort that arranges values in a different order on every single run.

Code

    const data = ['Orange', 'Ball', 'Sun', 'Apple', 10, 3, 22, 34, 66, 1];
    data.sort(() => 0.5 - Math.random());
    console.log(data);

Output

    ["Sun", "Orange", "Ball", "Apple", 66, 34, 3, 22, 10, 1] // first run
    [1, "Sun", "Orange", 22, 3, "Ball", 10, "Apple", 34, 66] // second run

The above examples show that the values are getting arranged differently on every run.

Live Demo

You May Also Like

Leave a Comment