1

I have an object which has multiple values.

{Object
  { value1: 1204
    value2: 5
    value3: blah
  },
  { value1: 1204
    value2: 3
    value3: blah
  },
  { value1: 942
    value2: 1
    value3: blah
  }, 
  etc
}

What I need to do is sort the object before I render it by value1 and value2. I haven't found any good solutions in my online searches.

What I have below obviously doesn't work. It first sorts by value1, then resorts by value2. I have tried a function within the sort similar to what is linked, and a few other tries. But I haven't been successful.

sortObject = (results) => {
  results.sort((a, b) => a.value1 - b.value1);
  results.sort((a, b) => a.value2 - b.value2);
  console.log(results);
  return results;
 };

What is an efficent way to sort my object?

staples
  • 424
  • 2
  • 8
  • 24

1 Answers1

5
results.sort((a, b) => a.value1 - b.value1 || a.value2 - b.value2);

If the subtraction of value1 is 0 (falsy so equal), it will then perform the secondary sort based on value2. You cannot have them in separate sorts as it does not remember previous sorts.

If you want the sort of value2 to have higher precidence, perform it first.

Taplar
  • 24,788
  • 4
  • 22
  • 35