0

Say for example I have an array of objects with the following basic structure:

{
    value1 : "VALUE"
  ,  value2 : "VALUE"
  ,  value3 : "VALUE"
}

Is there a way to sort this array in vanilla JavaScript where it sorts ascending on value1 and value2, but descending on value3? This is just a example of the kind of mixed sort I'm looking at. Pretty anywhere where sorting needs to be done on more than one object value, and it isn't only ascending or descending, but both.

For a bit of reference, I'm trying to build a results list and grant the user the ability to choose which values they want to sort on, and whether those values are sorted ascending or descending prior to being returned to the user.

Michael McCauley
  • 853
  • 1
  • 12
  • 37
  • Figured this was a duplicate, but couldn't find any results that matched close enough to what I needed. Ultimately designed a solution that used concepts from a couple different answers in the linked post. – Michael McCauley Nov 19 '18 at 20:45

1 Answers1

0

Sure, when you specify how to sort by implementing the comparison function that is passed to the sort() function: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

You can define a compare function for each of the sorting options and simply pass it into the sort() when it's time to sort the array.

Kon
  • 4,023
  • 4
  • 24
  • 38