Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save onildoaguiar/6cf7dbf9e0f0b8684eb5b0977b40c5ad to your computer and use it in GitHub Desktop.
Save onildoaguiar/6cf7dbf9e0f0b8684eb5b0977b40c5ad to your computer and use it in GitHub Desktop.
Sorting an array by date with Moment.js
const Moment = require('moment')
const array = [{date:"2018-05-11"},{date:"2018-05-12"},{date:"2018-05-10"}]
const sortedArray  = array.sort((a,b) => new Moment(a.date).format('YYYYMMDD') - new Moment(b.date).format('YYYYMMDD'))
console.log(sortedArray)
@tkud04
Copy link

tkud04 commented Feb 28, 2023

May I suggest moment().diff?

const sortedArray = array.sort((a, b) => a.diff(b))

diff takes the usual moment input, e.g. a date-formatted string.

God bless you chief!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment