How to use Intl.Collator In Javascript
The Intl.Collator object is a constructor for collators, which are objects that enable language-sensitive string comparison. This approach allows for more sophisticated sorting options, including case sensitivity and locale-specific rules.
Syntax:
new Intl.Collator([locales], [options])
Example: The below example uses Intl.Collator to sort an array of objects based on a key in JavaScript.
let arr = [
{ name: 'Arrays', topic: 'Data Structures' },
{ name: 'Recursion', topic: 'Algorithms' },
{ name: 'JavaScript', topic: 'Programming' }
];
// Create a collator for locale-aware string comparison
const collator = new Intl.Collator('en', { sensitivity: 'base' });
arr.sort((a, b) => collator.compare(a.name, b.name));
console.log(arr);
// Nikunj Sonigara
Output
[ { name: 'Arrays', topic: 'Data Structures' }, { name: 'JavaScript', topic: 'Programming' }, { name: 'Recursion', topic: 'Algorithms' } ]
How to Sort an Array of Objects Based on a Key in JavaScript ?
In JavaScript, sorting an array of objects based on the key consists of iterating over the array, applying the sort() method or other approaches, and arranging the array in the desired sorting order.
Table of Content
- Using sort() method
- Using Custom Sorting Function
- Using Lodash _.orderBy() Method
- Using Intl.Collator