Skip to content Skip to sidebar Skip to footer

Order Array Of Objects By Date

for example myArr= [ {name:'Joe', id:3, date: '2012.10.12'}, {name:'Ed', id:43, date: '2012.02.12'}, {name:'Mark', id:22, date: '2012.02.11'} ]; so how can I sort

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"