How can I sort an array of objects by a specific property in vanilla JavaScript?

Asked 1 year ago

0 Votes

1 Answer

18 Views

I have an array of objects, each with various properties. How can I efficiently sort this array based on a specific property, such as ‘price’ or ‘date’? I’m looking for a solution using vanilla JavaScript without any external libraries.

Here is my array:

const arrayOfObjects = [
  { name: 'Item 1', price: 20.5, date: '2023-01-15' },
  { name: 'Item 2', price: 15.7, date: '2023-02-10' },
  { name: 'Item 3', price: 25.0, date: '2023-01-05' }
];

1 Answer

Alright, cool. So, you want to sort your array of objects by a specific property like ‘price’ or ‘date’.

To sort by ‘price’:

arrayOfObjects.sort((a, b) => a.price - b.price);

This will sort your items from the lowest to highest price.

To sort by ‘date’:

arrayOfObjects.sort((a, b) => new Date(a.date) - new Date(b.date));

This sorts the items from the earliest to the latest date.

What this .sort() function does is it compares two elements at a time and sorts them based on the result. For prices, it’s straightforward subtraction. For dates, we convert the strings to Date objects first, then subtract. Easy peasy;)

Write your answer here

Top Questions