Sort Array of Objects by Property Values in JavaScript

Share Me
  •  
  •  
  •  
  • 1
  •  
  •  
  •  
  •  
  •  
  •  
  •  
    1
    Share

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.

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.

About Shahriar Sagor

My name is Shahriar sagor. I'm a developer. I live in Bangladesh and I love to write tutorials and tips that will help to other Developer's. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.

View all posts by Shahriar Sagor →

Leave a Reply

Your email address will not be published. Required fields are marked *

4 × 1 =