this is my test array:
let testArray = [{'Datum':'13/05/2024','ID':1},
{'Datum':'18/05/2013','ID':2},{'Datum':'01/05/2018','ID':3},
{'Datum':'31/05/2024','ID':4},{'Datum':'31/05/2024','ID':5}]
trying to order by Datum property ascending/descending order but it is not happening here is my logic:
_.orderBy(testArray, ['Datum'], ['asc']); //not working
using moment() js
_.orderBy(testArray, (o) => {
return moment(o.Datum).format('DD/MM/YYYY') //not happening either
}, ['asc']);
i tried _.sortby and sort..but array its not arranging correctly, any hints? thanks
2
Answers
You could build an ISO 8601 string and sort by string.
Your code wasn’t working because you tried to format the date instead of actually telling Moment.js what format the date is. Instead of using
moment(o.Datum).format("DD/MM/YYYY")
, you should usemoment(o.Datum, "DD/MM/YYYY")
. That said below are the 2 solutions:Vanilla js with moment
This works by first mapping an array of items (item.Datum) into Moment.js date objects using the format DD/MM/YYYY. Then, it sorts these date objects in both ascending and descending order.
The most important thing here is sorting part and how
Array.sort()
works . Here’s the basic working :And using
moment(...).diff(...)
returns the difference i.e number so,a.diff(b)
returns a negative number if a is before b, zero if a is the same as b, and a positive number if a is after b.With lodash & moment ( yours corrected one )
This approach uses
_.orderBy
function for sorting. The sorting key is a parsed date, which is created by passing the Datum value through Moment.js with the format DD/MM/YYYY. By specifying ["desc"], the array is sorted in descending order.