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:
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
Contact Us