1
[
    { 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?

8
  • 4
    What have you tried so far? Commented Feb 27, 2022 at 17:23
  • using the index of the list to get into the first aray and then tried to applya an index Commented Feb 27, 2022 at 17:29
  • and then i tried two for loops one to select the first aray and then get in the second Commented Feb 27, 2022 at 17:30
  • @nikstreat You will be able to get much better answers on here if you include the code that you tried to get working :) Commented Feb 27, 2022 at 17:30
  • when i googled i saw that this kind of stuff i tried is just not an option. Im looking for a way to be able ro reach scores so theat i can manipulate it but all i find is selekting an aray by thr value of the second item Commented Feb 27, 2022 at 17:34

3 Answers 3

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

You could take a Map for all sums and the object as key without mutating data.

const
    data = [{ name: 'Joe', scores: [1, 2, 3] }, { name: 'Jane', scores: [1, 4, 3] }, { name: 'John', scores: [1, 2, 1] }],
    add = (a, b) => a + b,
    sums = new Map(data.map(o => [o, o.scores.reduce(add, 0)]));

data.sort((a, b) => sums.get(b) - sums.get(a) || a.name.localeCompare(b.name));

console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Comments

0

The lodash package could be handy

const lodash = require('lodash')

const list = [
  { name: 'Joe', scores: [1, 2, 4] },
  { name: 'Jane', scores: [1, 2, 3] },
  { name: 'John', scores: [1, 2, 4] }
]

const listWithSum = list.map(item => {
  return {
    ...item,
    sum: lodash.sum(item.scores)
  }
})

const sortedList = lodash.orderBy(listWithSum, ['score', 'name'], ['desc', 'desc'])

console.log(sortedList)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.