How to use Custom Sorting Function In Javascript
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' } ]
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