Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

179
Views
JavaScript: Sort array of objects by computed property or by an existing property if equal
[
    { 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?

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report

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

about 4 years ago · Juan Pablo Isaza Report

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)
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!