Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading