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)
@danieldourado
Copy link

You guys rock!

@igorturturro
Copy link

Working smoothly!

@adityaTekale
Copy link

@jonasholtkamp thanks!

@simonescob
Copy link

The following also takes seconds and milliseconds into account and is a bit shorter.

let sortedArray = array.sort((a, b) => a.valueOf() - b.valueOf())

Thanks for this aport. Using moment in the code will be so:

let sortedArray = array.sort((a,b) => moment(a).valueOf() - moment(b).valueOf())

@matheop
Copy link

matheop commented Aug 14, 2021

simple and clear, thanks!

@jlhernando
Copy link

This worked for me really nicely! thanks @jonasholtkamp

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.

@Fernando74lr
Copy link

Thanks a lot!

@leunglong0123
Copy link

Thaknks!

@Ba7er
Copy link

Ba7er commented Dec 21, 2021

Thanks.

@sabricalivar
Copy link

sabricalivar commented Mar 5, 2022

Thanks!!! <3 here I am after trying everything... loving you for this! (and dancing for victory of course!)

@shakib04
Copy link

shakib04 commented Nov 1, 2022

Thanks!!! <3 here I am after trying everything... loving you for this! (and dancing for victory of course!)

hahahaha

@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