Home Javascript Sort Array of Objects by Property Values in JavaScript

Sort Array of Objects by Property Values in JavaScript

by Shahriar Sagor
Sort Array of Objects by Property

Hello JavaScript lovers
Today in this example, I will teach you to write a JavaScript program.Where you can sort an array of objects by its property values. Here i will show you Sort Array of Objects by Property Values in JavaScript.

To understand about this example, you should have a good knowledge of the following JavaScript programming topics:

Example 1: Sort Array by Property Name

// program to sort array by property name

function compareName(a, b) {

    // converting to uppercase to have case-insensitive comparison
    const name1 = a.name.toUpperCase();
    const name2 = b.name.toUpperCase();

    let comparison = 0;

    if (name1 > name2) {
        comparison = 1;
    } else if (name1 < name2) {
        comparison = -1;
    }
    return comparison;
}

const students = [{name: 'Sara', age:24},{name: 'John', age:24}, {name: 'Jack', age:25}];

console.log(students.sort(compareName));

Output

[{name: "Jack", age: 25},
{name: "John", age: 24},
{name: "Sara", age: 24}]

In this program, the sort() method is use to Sort an Array by its property values.

The sort() method sorts its elements according to the values returned by a custom sort function (compareName in this case).

Example 2: Sort Array by Property Age

// program to sort array by property name

function compareAge(a, b) {

    return a.age - b.age;
}

const students = [{name: 'Sara', age:24},{name: 'John', age:22}, {name: 'Jack', age:27}];

console.log(students.sort(compareAge));
[{name: "John", age: 22},
{name: "Sara", age: 24},
{name: "Jack", age: 27}]

In this program, the sort() method is used to sort an array element by the age property.

To compare the age property of two objects, we can simply subtract them.

close

You may also like

Leave a Comment