Reputation: 341
I'm currently getting data from an API and I'm coming across a problem when trying to sort the data in the client side view, by date.
This is the data I'm receiving (about 20+ but I'm giving one example with some sample data filled in)
address: "1212 Test Ave"
address2: ""
checkNumber : ""
city: "La Grange"
country: ""
email: "[email protected]"
firstName: "John"
id: "103138"
lastName: "Dough"
middleName: ""
organization: ""
partnerId: "108765.1"
paymentAmount: "$5.00 "
paymentDate: "7/30/2015"
paymentType: "CASH"
phoneNumber: "(999)999-9999"
spouseFirstName: ""
spouseLastName: ""
spouseTitle: ""
state: "IL"
title: "Mr. & Mrs."
zipCode: "60525-2544"
There is 20+ of these in an array called "contributions". How would one sort this array by paymentDate "mm/dd/yyyy". Obviously it would be year sorted first, then month, then day.
I have seen code that somewhat does this but I'm having trouble implementing it from an array that isn't solely an array of dates.
It also does not sort the days correctly, just months/year. The years is a separate array that I pulled all the dates out of for a different purpose.
this.years.sort(function (a, b) { return a - b });
But I am trying to sort the entire array listed in the first code block by date.
If anyone could help me or guide me in the right direction, that would be a massive help!
Thanks!
Additional Information using @mplungjan method. This is the output of it all when sent through to the table.
Upvotes: 0
Views: 3514
Reputation: 178094
The sort needs date.getTime()-date.getTime()
In this case you can leave off the getTime since it will be used anyway
var contributions = [
{paymentDate: "9/2/2014"},
{paymentDate: "9/7/2014"},
{paymentDate: "10/8/2015"},
{paymentDate: "1/9/2014"},
{paymentDate: "3/9/2015"}
]
contributions.sort(function(a, b) {
return new Date(a.paymentDate) - new Date(b.paymentDate)
})
console.log(contributions)
Upvotes: 4
Reputation: 76601
This is an easy-to-understand solution:
for (var i = 0; i < contributions.length; i++) {
var dateI = new Date(contributions[i].paymentDate);
for (var j = i + 1; j < contributions.length; j++) {
var dateJ = new Date(contributions[j].paymentDate);
if (dateI > dateJ) {
var aux = contributions[i];
contributions[i] = contributions[j];
contributions[j] = aux;
dateI = dateJ;
}
}
}
If you want an already existent solution, then:
contributions.sort(function(a, b) {
return new Date(a.paymentDate) - new Date(b.paymentDate);
});
Upvotes: 1