Categories
JavaScript Answers

How to sort an array of objects by date with JavaScript?

Spread the love

To sort an array of objects by date with JavaScript, we call the sort method.

For instance, we write

const recent = [
  { id: 123, age: 12, start: "10/17/2022 13:07" },
  { id: 13, age: 62, start: "07/30/2022 16:30" },
];
const sorted = recent.sort((a, b) => {
  return new Date(a.start).getTime() - new Date(b.start).getTime();
});

to call recent.sort with a callback that gets the timestamp of the start property of 2 of the objects in recent with getTime and then compare them by subtracting them to return a number that determines the sorting order.

a is sorted after b if the number returned is bigger than 0.

a is sorted before b if the number returned is less than 0.

And the original order is kept if it’s 0.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *