How to useIntl.Collator for Locale-Aware String Comparison in Javascript

In this approach, we use the Intl.Collator object for locale-aware string comparison, which provides better performance and more options for locale-sensitive string comparison.

Example:

JavaScript
const GFG_object = [
    { name: "Nikunj", age: 30 },
    { name: "Dhruv", age: 25 },
    { name: "Yash", age: 35 }
];

const collator = new Intl.Collator('en', { sensitivity: 'base' });

let result = GFG_object.sort((a, b) =>
    collator.compare(a.name, b.name));
 
console.log(result);

Output
[
  { name: 'Dhruv', age: 25 },
  { name: 'Nikunj', age: 30 },
  { name: 'Yash', age: 35 }
]


Sort array of objects by string property value in JavaScript

In this article, we will see how to sort an array of objects by string property value in JavaScript. The array of objects can be sorted by using a user-defined function. 

Here we have some common approaches to sorting an array of objects by string property value

  • Using sort() with a custom compare function
  • sorting by a user-defined function
  • Using sort() with a comparison function and the toLowerCase() method

Similar Reads

Approach 1: Using sort() with a custom compare function

In this approach, sort() is used with a custom compare function that utilizes localeCompare() to sort the array of objects by a string property value....

Approach 2: sorting by a user-defined function.

This function compares the array of objects by its property. this example compares the l_name of objects and if l_name is small then it places into the left otherwise place it into the right position....

Approach 3: Using sort() with a comparison function and the toLowerCase() method

In this approach, sort() with a comparison function and toLowerCase() to sort an array of objects case-insensitively based on a string property....

Approach 4: Using Intl.Collator for Locale-Aware String Comparison

In this approach, we use the Intl.Collator object for locale-aware string comparison, which provides better performance and more options for locale-sensitive string comparison....

Contact Us