How to use sort() method In Javascript
In this approach, we will use the sort() method with a custom comparator function that compares the name property of objects using localeCompare() method, which makes sure that the array is sorted alphabetically by the name key.
Syntax:
array.sort([compareFunction])
Example: The below example uses the sort() method 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' }
];
arr.sort((a, b) => a.name.localeCompare(b.name));
console.log(arr);
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
Contact Us