Sort an array of objects by date using moment

Sorting and ordering an array is quite easy, just use array.sort and pass the function which returns the difference. For instance:

  const arr = [0, 10, 2, 3]
  const newarr = arr.sort((a, b) => {
    return a -b;   
  })

Last week I needed to order an array of objects by their date. The array uses momentjs to render the dates. Looking at the moment documentation, very well written, I found easily the solution:

    const arr = [
      {_id: 1, createdAt: moment("Sat Jan 07 2018 11:50:21 GMT+0000 (WET)")},
      {d_id: 2, createdAt:moment("Sat Jan 06 2018 11:50:21 GMT+0000 (WET)")}
    ]

    const newarr = arr.sort((a, b) => {
      return moment(a.createdAt).diff(b.createdAt)
    })

This will sort the array by date with moment. Easy peasy :smile:

Loading...