2

I have the following array of objects:

const items = [
    { name: "Different Item", amount: 100, matches: 2 },
    { name: "Different Item", amount: 100, matches: 2 },
    { name: "An Item", amount: 100, matches: 1 },
    { name: "Different Item", amount: 30, matches: 2 }
]

I need to sort these by matches and amount, so the final result looks like this:

[
    { name: "Different Item", amount: 100, matches: 2 },
    { name: "Different Item", amount: 100, matches: 2 },
    { name: "Different Item", amount: 30, matches: 2 },
    { name: "An Item", amount: 100, matches: 1 }
]

The first priority is to sort everything by matches, and then within those, I need to sort them by amount. I know I can sort by just matches or just amount like so:

items.sort((a, b) => a.matches - b.matches);

But how can I sort by both?

APixel Visuals
  • 1,508
  • 4
  • 20
  • 38
  • items.sort ( 1. Sort by matches. 2a. If equal, sort by amount. 2b. if not equal, do not do amount sort. ). That is, equal "matches" does not resolve lesser or greater so go to the next sort. Repeat this pattern for all sort criteria. If they all resolve to equal, then the 2 items are equal and Javascript will not change their order. Once a sort resolves "not equal" then we know which is lesser.greater - no matter how subsequent criteria resolve. – radarbob Dec 06 '19 at 00:04

2 Answers2

3

You can use Array#sort. Objects will get sorted based firstly on matches then on amount.

const items = [
    { name: "Different Item", amount: 90, matches: 2 },
    { name: "Different Item", amount: 100, matches: 1 },
    { name: "An Item", amount: 80, matches: 1 },
    { name: "Different Item", amount: 30, matches: 2 },
    { name: "Different Item", amount: 40, matches: 1 },
    { name: "Different Item", amount: 50, matches: 1 },
    { name: "An Item", amount: 10, matches: 1 },
    { name: "Different Item", amount: 20, matches: 2 },
];

const r = [...items].sort((a, b) => b.matches - a.matches || b.amount - a.amount);

console.log(r);
kind user
  • 40,029
  • 7
  • 67
  • 77
0

Another way to express sorting based on two critiera with Array#sort would be:

const items = [
    { name: "Different Item", amount: 100, matches: 2 },
    { name: "Different Item", amount: 100, matches: 2 },
    { name: "An Item", amount: 100, matches: 1 },
    { name: "Different Item", amount: 30, matches: 2 }
]

const result = items.sort((a, b) => {
  
  const matches = b.matches - a.matches;
  
  // If a.matches and b.matches are not the same,
  // sort this a and b pair based on matches in
  // descending order
  if(matches !== 0) {
    return matches;
  }
  
  // Here, the a and b pair have the same matches
  // value, so sort based on seondary criteria; 
  // amount in descending order
  return b.amount - a.amount;
});

console.log(result);
Dacre Denny
  • 29,664
  • 5
  • 45
  • 65