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().

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.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.

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

Similar Reads

Using sort() with compare function

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....

Using sort() method

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....

Using localeCompare() for string values

localeCompare() compares strings in alphabetical order. Sorting objects by a string property results in an alphabetically sorted array....

Using external libraries like Lodash

To sort an array of objects using Lodash, first ensure Lodash is imported. Then, utilize _.sortBy(array, ‘property’) to sort the array by the specified property, such as age or name. This method returns a new sorted array....