[
{ name: 'Joe', scores: [1, 2, 3] },
{ name: 'Jane', scores: [1, 2, 3] },
{ name: 'John', scores: [1, 2, 3] }
]
how do I make a function that sorts the elements first by the sum in scores and later by name?
>Solution :
Using Array#sort, sort the array by the sum of scores, or name as fallback (using String#localeCompare)
const arr = [ { name: 'Joe', scores: [1] }, { name: 'Jane', scores: [1, 2] }, { name: 'John', scores: [1, 2] } ];
const sum = (arr = []) => arr.reduce((total, num) => total + num, 0);
const sorted = arr.sort((a, b) =>
sum(b.scores) - sum(a.scores) || a.name.localeCompare(b.name)
);
console.log(sorted);