Order Array Of Objects By Date
Solution 1:
Assuming the dates are just strings formatted as in your code, you can do this:
myArr.sort( (a,b) => a.date.localeCompare(b.date) )
The sort
method takes as a parameter a function that will be called every time it needs to compare two elements of the array. So to sort by a particular field, you pass a function that compares those fields of the two objects passed in.
The sort comparator function has to return a special value indicating the correct order: -1 if the first parameter (conventionally called a
) should come before the second (b
); 1 if b
should come before a
; or 0 if they're equal (so the order doesn't matter). Fortunately, there's already a method that compares strings and returns the proper value for sort
(if you call it on a
and pass b
as a parameter): localeCompare
. Since the fields you're comparing are strings, you can just call that on the fields in your comparison function to return the proper value for the sort.
Post a Comment for "Order Array Of Objects By Date"