Skip to Content

How to Sort an Array of Objects in JavaScript

In this tutorial, we'll explore multiple ways to sort an array of objects in JavaScript and create a custom function to handle the dirty work for us.

Sort an Array of Objects

First, let's create an array of objects named people. Each object will contain the person's first name, last name, and age:

var people = [
{
first_name: "John",
last_name: "Doe",
age: 35
},
{
first_name: "Jane",
last_name: "Doe",
age: 27
},
{
first_name: "Blake",
last_name: "Smith",
age: 44
}
];

And now, we'll sort that array by creating a custom function named compare():

function compare(array, sort) {
return array.sort(function(a, b) {
if (a[sort] > b[sort]) {
return 1;
}
else {
return -1;
}
});
}

This function accepts two parameters:

  • array: The variable containing the array of objects.
  • sort: The object item to sort within each object.

Setting these parameters dynamically allows us to sort an array by any of the contained object names, and to reuse the same function as many times as needed. This alternatively allows us to pass last_name or age as the sort parameter for a different result.

The Array sort() method is then called, passing two copies of our array into the function, a and b. A comparison is run between the two array copies, returning 1 for the object value to take precendence in sorting, and -1 for the opposite.

Shorthand Sort Method

If you're a fan of shorthand methods, we could also condense the code down a bit using an inline if statement and arrow function:

function compare(array, sort) {
return array.sort((a, b) => (a[sort] > b[sort]) ? 1 : -1);
}

Conclusion

Here, you learned two different ways to sort an array of objects in JavaScript and how to create a custom function for wrapping this functionality for multiple uses.

Created: May 13, 2022

Comments

There are no comments yet. Start the conversation!

Leave a Comment

Comment Etiquette: Wrap code in a <code> and </code>. Please keep comments on-topic, do not post spam, keep the conversation constructive, and be nice to each other.