How to Sort an Array of Objects Based on a Key in JavaScript ?
Last Updated :
29 May, 2024
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.
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.
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.
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.
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.
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' }
]
Similar Reads
How to sort an array of object by two fields in JavaScript ? We have given an array of objects and the task is to sort the array of elements by 2 fields of the object. There are two methods to solve this problem which are discussed below: Approach 1:First compare the first property, if both are unequal then sort accordingly.If they are equal then do the same
3 min read
How to Sort JSON Object Arrays Based on a Key? Sorting is the process of arranging elements in a specific order. In JavaScript, we can sort a JSON array by key using various methods, such as the sort() function. Along with this, we can use various other approaches and methods that are implemented in this article. Below are the approaches to sort
3 min read
How to Move a Key in an Array of Objects using JavaScript? The JavaScript array of objects is a type of array that contains JavaScript objects as its elements.You can move or add a key to these types of arrays using the below methods in JavaScript:Table of ContentUsing Object Destructuring and Map()Using forEach() methodUsing for...of LoopUsing reduce() met
5 min read
How to Sort/Order Keys in JavaScript Objects? To sort or order keys in JavaScript objects, first get the keys as an array and then apply a sorting mechanism to arrange them.Below are the approaches to sort the keys in JavaScript Objects:Table of ContentUsing forEach() methodUsing reduce methodApproach 1: Using forEach() methodSort the keys of a
2 min read
How to Sort an Array Based on the Length of Each Element in JavaScript? Imagine you have a list of words or groups of items, and you want to arrange them in order from shortest to longest. This is a pretty common task in JavaScript, especially when working with text or collections of things. By sorting your list in this way, you can make sense of your data and make it e
3 min read
How to compare Arrays of Objects in JavaScript? In JavaScript, comparing arrays of objects can be more complex than comparing primitive data types. We will discuss different ways to compare arrays of objects effectively, with detailed code examples and explanations.Syntax: Before going to detail the comparison techniques, let's first understand h
5 min read
How to Access Array of Objects in JavaScript ? Accessing an array of objects in JavaScript is a common task that involves retrieving and manipulating data stored within each object. This is essential when working with structured data, allowing developers to easily extract, update, or process information from multiple objects within an array.How
4 min read
JavaScript - Sort JS Arrays of Objects by Date Key The following approaches can be used to sort the array of objects by Date as KeyUsing Array.sort() with Comparison FunctionUse the comparison function to sort the array of objects (complex array).JavaScriptconst arr = [ { name: 'Geeks', date: '2022-03-15' }, { name: 'Abc', date: '2022-03-12' }, { na
3 min read
Sort an array of objects using Boolean property in JavaScript Given the JavaScript array containing Boolean values. The task is to sort the array on the basis of Boolean value with the help of JavaScript. There are two approaches that are discussed below: Table of Content Using Array.sort() Method and === OperatorUsing Array.sort() and reverse() MethodsUsing a
2 min read
How to Sort JSON Array in JavaScript by Value ? Sorting is the process of arranging elements in a specific order. In JavaScript, you can sort a JSON array by value using various methods as listed and discussed below with their practical implementation. Table of Content Using sort() FunctionUsing Array.prototype.reduce()Using Bubble SortUsing sort
3 min read