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
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' } ]
Using Custom Sorting Function
In this approach, we are using the Custom Sorting Function where the array is iterated and the adjacent elements are swapped by comparing their properties using localeCompare() method. This continues till no more swaps are required.
Syntax:
function function_name()
{
// sorting logic
}
Example: The below example uses the Custom Sorting Function 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' }
];
function approach2Fn(arr, k) {
let temp;
do {
temp = false;
for (let i = 0; i < arr.length - 1; i++)
{
if (arr[i][k].
localeCompare(arr[i + 1][k]) > 0)
{
[arr[i], arr[i + 1]] =
[arr[i + 1], arr[i]];
temp = true;
}
}
} while (temp);
return arr;
}
arr = approach2Fn(arr, 'name');
console.log(arr);
Output
[ { name: 'Arrays', topic: 'Data Structures' }, { name: 'JavaScript', topic: 'Programming' }, { name: 'Recursion', topic: 'Algorithms' } ]
Using Lodash _.orderBy() Method
In this approach, we will use the Lodash _.orderBy() method. If orders are unspecified, then all values are sorted in ascending order. Otherwise, order of corresponding values specifies an order of desc for descending or asc for ascending sort.
Syntax:
_.orderBy(Collection, [ iteratees ], [ orders ]);
Example: The below example uses the Lodash _.orderBy() method to sort an array of objects based on a key in JavaScript.
const _ = require('lodash');
let arr = [
{ name: 'Arrays', topic: 'Data Structures' },
{ name: 'Recursion', topic: 'Algorithms' },
{ name: 'JavaScript', topic: 'Programming' }
];
arr = _.orderBy(arr, ['name'], ['asc']);
console.log(arr);
Output:
[
{ name: 'Arrays', topic: 'Data Structures' },
{ name: 'JavaScript', topic: 'Programming' },
{ name: 'Recursion', topic: 'Algorithms' }
]
Using Intl.Collator
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' } ]