Categories
JavaScript Answers

How to sort array of objects by single key with date value with JavaScript?

Spread the love

To sort array of objects by single key with date value with JavaScript, we can subtract the timestamps.

For instance, we write

const arr = [
  {
    updatedAt: "2022-01-01T06:25:24Z",
    foo: "bar",
  },
  {
    updatedAt: "2022-01-09T11:25:13Z",
    foo: "bar",
  },
  {
    updatedAt: "2022-01-05T04:13:24Z",
    foo: "bar",
  },
];
const sorted = arr.sort(
  (a, b) => +new Date(a.updatedAt) - +new Date(b.updatedAt)
);

to call arr.sort with a callback that converts updateAt to dates with the Date constructor.

And then we convert them to timestamps in milliseconds with +.

Finally, we subtract them to compare them.

A new array with the sorted values is returned.

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 *