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 Filter an Array of Objects Based on Multiple Properties in JavaScript ?
Filtering an array of objects based on multiple properties is a common task in JavaScript. It allows us to selectively extract items from an array that satisfy specific conditions. We will explore different approaches to achieve this task.These are the following approaches:Table of ContentUsing the
6 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 Convert an Array of Objects to Map in JavaScript?
Here are the different methods to convert an array of objects into a Map in JavaScript1. Using new Map() ConstructorThe Map constructor can directly create a Map from an array of key-value pairs. If each object in the array has a specific key-value structure, you can map it accordingly.JavaScriptcon
3 min read
How to convert a map to array of objects in JavaScript?
A map in JavaScript is a set of unique key and value pairs that can hold multiple values with only a single occurrence. Sometimes, you may be required to convert a map into an array of objects that contains the key-value pairs of the map as the values of the object keys. Let us discuss some methods
6 min read
How to use forEach with an Array of Objects in JavaScript ?
Using the forEach() method with an array of objects in JavaScript is essential for iterating over collections and performing operations on each object. This guide explores effective techniques to utilize forEach() for array manipulation, enhancing your coding skills. Syntax: array.forEach( function(
3 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