-3

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"}

Is there anyway I can 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 Had 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 Tried to Research to Help Me:

Community
  • 1
  • 1
VoidKing
  • 5,922
  • 8
  • 44
  • 75

1 Answers1

4

"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."

eventJsonArr.sort(function(a, b) {  //     eventYear DESC
    return a.eventYear !== b.eventYear ? b.eventYear - a.eventYear :
                                         a.eventName.localeCompare(b.eventName);
});                                 //     eventName ASC
Blue Skies
  • 2,847
  • 14
  • 19