Q:

JavaScript - Sort array by two integer properties

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?

A:

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);

