# How to sort an array by date value in JavaScript

> Learn how to sort a JavaScript array of objects by a date property, using sort() with a callback that subtracts the dates, and slice() to avoid mutating it.

Author: [Flavio Copes](https://flaviocopes.com/about/) | Published: 2019-07-14 | Topics: [JavaScript](https://flaviocopes.com/tags/js/) | Canonical: https://flaviocopes.com/how-to-sort-array-by-date-javascript/

Say you have an array of objects like this, which contains a set of [date objects](https://flaviocopes.com/javascript-dates/):

```js
const activities = [
  { title: 'Hiking', date: new Date('2019-06-28') },
  { title: 'Shopping', date: new Date('2019-06-10') },
  { title: 'Trekking', date: new Date('2019-06-22') }
]
```

You want to sort those activities by the `date` property.

You can use the `sort()` method of [`Array`](https://flaviocopes.com/javascript-array/), which takes a callback function, which takes as parameters 2 objects contained in the array (which we call `a` and `b`):

```js
const sortedActivities = activities.sort((a, b) => b.date - a.date)
```

When we return a positive value, the function communicates to `sort()` that the object `b` takes precedence in sorting over the object `a`. Returning a negative value will do the opposite.

The `sort()` method returns a new sorted array, but it also sorts the original array in place. Thus, both the `sortedActivities` and `activities` arrays are now sorted. One option to protect the original array from being modified is to use the `slice()` method to create a copy of the array prior to sorting, as follows:

```js
const sortedActivities = activities.slice().sort((a, b) => b.date - a.date)
```

You can generate this kind of comparator function interactively with the [sort comparator builder](https://flaviocopes.com/tools/sort-comparator/).
