How to use localeCompare() for string values In Javascript
localeCompare() compares strings in alphabetical order. Sorting objects by a string property results in an alphabetically sorted array.
Example: The employees_details array is sorted alphabetically based on the name property using localeCompare().
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.name.localeCompare(b.name));
console.log(employees_details);
Output
[ { name: 'Mohan', age: 30 }, { name: 'Ram', age: 17 }, { name: 'Shyam', age: 15 }, { name: 'Shyam', age: 17 } ]
How to sort an array of objects by property values ?
In this article, we will try to understand 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.
There are several methods that can be used to sort an array of objects by property values
Table of Content
- Using sort() with compare function
- Using sort() method
- Using localeCompare() for string values
- Using external libraries like Lodash