Categories
JavaScript Answers

How to Sort a JavaScript Array by ISO 8601 Date?

Spread the love

Sometimes, we want to sort a JavaScript array by ISO 8601 date.

In this article, we’ll look at how to sort a JavaScript array by ISO 8601 date.

Sort a JavaScript Array by ISO 8601 Date

To sort a JavaScript array by ISO 8601 date, we can use the JavaScript array’s sort method.

For instance, we can write:

const arr = [{
    name: 'oldest',
    date: '2001-01-17T08:00:00Z'
  },
  {
    name: 'newest',
    date: '2011-01-28T08:00:00Z'
  },
  {
    name: 'old',
    date: '2009-11-25T08:00:00Z'
  }
];

const sorted = arr.sort((a, b) => {
  return (a.date < b.date) ? -1 : ((a.date > b.date) ? 1 : 0)
});
console.log(sorted)

We have the arr array that we want to sort by the date value.

Then we call arr.sort with a callback that compares the strings to compare the date strings directly by their values lexigraphically.

If a.date is less than b.date we return keep their order.

Otherwise, if a.date is bigger than b.date, we return 1 to reverse their order.

If they’re the same, we return 0.

Therefore, sorted, is:

[
  {
    "name": "oldest",
    "date": "2001-01-17T08:00:00Z"
  },
  {
    "name": "old",
    "date": "2009-11-25T08:00:00Z"
  },
  {
    "name": "newest",
    "date": "2011-01-28T08:00:00Z"
  }
]

Conclusion

To sort a JavaScript array by ISO 8601 date, we can use the JavaScript array’s sort method.

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 *