Open In App

How to Sort an Array of Objects Based on a Key in JavaScript ?

Last Updated : 27 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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' }
]


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads