Skip to content
Related Articles
Open in App
Not now

Related Articles

How to sort an array of objects by property values ?

Improve Article
Save Article
Like Article
  • Last Updated : 25 Jan, 2023
Improve Article
Save Article
Like Article

In this article, we will try to understand that how to sort an array of objects by property values in JavaScript with the help of certain examples.

Pre-requisite: Array of Objects in JavaScript

Example:

Input:
[
    { name: "Ram", age: 17 },
    { name: "Mohan", age: 30 },
    { name: "Shyam", age: 15 },
    { name: "Shyam", age: 17 },
]
Output:
[
    { name: 'Shyam', age: 15 },
    { name: 'Ram', age: 17 },
    { name: 'Shyam', age: 17 },
    { name: 'Mohan', age: 30 }
]

 

Explanation:

  • Pick any property and sort the object on the basis of that property’s values in other objects inside an array of objects.

After understanding the desired task from the above example, let us quickly see the following approaches through which we may understand as well as solve solutions for the above-shown task.

Approach 1:

  • Here we will use the sort() method and inside the sort method, we will explicitly define a compare method for comparing values as per the user’s need.
  • Then inside that compare() method, we will use if-else statements in order to check property values.

Example: Below is the implementation of the above approach.

Javascript




let employees_details = [
    { name: "Ram", age: 17 },
    { name: "Mohan", age: 30 },
    { name: "Shyam", age: 15 },
    { name: "Shyam", age: 17 },
];
  
let compare = (a, b) => {
    if (a.age < b.age) {
        return -1;
    }
    if (a.age > b.age) {
        return 1;
    }
    return 0;
};
  
employees_details.sort(compare);
console.log(employees_details);


Output:

[
    { name: 'Shyam', age: 15 },
    { name: 'Ram', age: 17 },
    { name: 'Shyam', age: 17 },
    { name: 'Mohan', age: 30 }
]

Approach 2:

  • This approach also uses the sort() method but unlike the previous approach here we will shorten the syntax and do all the work as inline itself.
  • In the inline technique, we will use the ternary operator concept in order to compare two different values and then return the corresponding results.

Example: Below is the implementation of the above approach.

Javascript




let employees_details = [
    { name: "Ram", age: 17 },
    { name: "Mohan", age: 30 },
    { name: "Shyam", age: 15 },
    { name: "Shyam", age: 17 },
];
  
employees_details.sort((a, b) => (
    a.age > b.age ? 1 : b.age > a.age ? -1 : 0));
console.log(employees_details);


Output:

[
    { name: 'Shyam', age: 15 },
    { name: 'Ram', age: 17 },
    { name: 'Shyam', age: 17 },
    { name: 'Mohan', age: 30 }
]

My Personal Notes arrow_drop_up
Like Article
Save Article
Related Articles

Start Your Coding Journey Now!