I have the following array of objects:
eventJsonArr[0] = { eventName: "Event One", eventYear "2012"}
eventJsonArr[1] = { eventName: "Event Two", eventYear "2011"}
eventJsonArr[2] = { eventName: "Event Three", eventYear "2012"}
eventJsonArr[3] = { eventName: "Event Four", eventYear "2013"}
eventJsonArr[4] = { eventName: "Event Five", eventYear "2010"}
eventJsonArr[5] = { eventName: "Event Six", eventYear "2011"}
How can I sort this array based on each object's properties? In short: all I need is to be able to sort the array of objects first by eventYear
, in descending order, then by eventName
in ascending order.
I guess I need it to mimic exactly what SQL would do if eventName
and eventYear
were columns, each index of the array were rows, and it contained ORDER BY eventYear DESC, eventName ASC
.
I need this to use with a "page preview", so it has to behave exactly like the page I have setup that queries the actual database (as described above).
Additional Info:
I am actually .push()
ing the values one at a time in a jQuery .each()
loop, so if something needs to be done as I'm actually adding the values to the array, as opposed to actually sorting the array of complete values, this can be done (although, I'm not sure of the logic needed there).
Here's what I tried before posting this question:
eventJsonArr.sort() //As a start, just to see what it did.
And then:
evenJsonArr.sort(function(a, b) { //I got the basic function to sort, which it did.
a.eventYear - b.eventYear
});
Beyond this function, I really couldn't find anything that was relevant to my situation. At least not that I found.
Here are some pages that I researched:
"All I need is to be able to sort the array of objects first by
eventYear
, indescending
order, then byeventName
inascending
order."
eventJsonArr.sort(function(a, b) { // eventYear DESC
return a.eventYear !== b.eventYear ? b.eventYear - a.eventYear :
a.eventName.localeCompare(b.eventName);
}); // eventName ASC