How to sort an array in Javascript

How to sort an array in Javascript

Here’s how to sort an array of objects in Javascript.

We start with an array of object like so:

const people = [] 

people.push({name: "John", age: 36, eyeColor: "hazel"});
people.push({name: "Pam", age: 63, eyeColor: "blue"});
people.push({name: "Tim", age: 24, eyeColor: "brown"});
people.push({name: "Julia", age: 20, eyeColor: "brown"});
people.push({name: "Roberta", age: 45, eyeColor: "green"});

We want to order the objects in the array by the age attribute, in descending order, from oldest to youngest.

Array has a sort() method that we can use in this case.

The method takes a function that can be used to specify the sort order of the elements in the array.

In our case, we want to sort by age descending, so we call sort() like so:

people.sort((a, b) => b.age - a.age);

sort() orders the array in place, so it mutates it. If we want to keep the array in its original state, we can use the toSorted() method, which behaves the same way, but returns a new array.

const peopleOrderedByAge = people.toSorted((a, b) => b.age - a.age);
← All posts Recent blog posts →