1

Consider the following scenario, where I have to sort a list of students by both name and scores.

[
 {
  name: 'Max',
  score: 94
 },
 {
  name: 'Jerome',
  score: 86
 },
 {
  name: 'Susan',
  score: 86
 },
 {
  name: 'Abel',
  score: 86
 },
 {
  name: 'Kevin',
  score: 86
 }
]

I want to sort the list by the student who scored the highest, but if two or more students have the same score, then I want to sort those students alphabetically. For the above case, the result should be as below:

[
 {
  name: 'Max',
  score: 94
 },
 {
  name: 'Abel',
  score: 86
 },
 {
  name: 'Jerome',
  score: 86
 },
 {
  name: 'Kevin',
  score: 86
 },
 {
  name: 'Susan',
  score: 86
 }
]

How can I achieve this? Is there any lodash function that I can use, or is it possible with pure JavaScript?

4 Answers4

5

No library needed, just compare the scores, and if that comes out to 0, compare the names:

const arr=[{name:'Max',score:94},{name:'Jerome',score:86},{name:'Susan',score:86},{name:'Abel',score:86},{name:'Kevin',score:86}]

console.log(
  arr.sort((a, b) => b.score - a.score || a.name.localeCompare(b.name))
);
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
1

Try the following:

var arr = [
 {
  name: 'Max',
  score: 94
 },
 {
  name: 'Jerome',
  score: 86
 },
 {
  name: 'Susan',
  score: 86
 },
 {
  name: 'Abel',
  score: 86
 },
 {
  name: 'Kevin',
  score: 86
 }
];
arr.sort((a,b)=>{
 return (b.score - a.score) || a.name.localeCompare(b.name);
});
console.log(arr);
amrender singh
  • 7,949
  • 3
  • 22
  • 28
1

You could sort by _.sortBy and take a list of propertis and another for the order.

var array = [{ name: 'Max', score: 94 }, { name: 'Jerome', score: 86 }, { name: 'Susan', score: 86 }, { name: 'Abel', score: 86 }, { name: 'Kevin', score: 86 }];

console.log(_.sortBy(array, ['score', 'name'], ['desc', 'asc']))
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
1

First sort the array by score and if both scores are equal then sort it by name. Consider below code for the same:

let obj = [
 {
  name: 'Max',
  score: 94
 },
 {
  name: 'Jerome',
  score: 86
 },
 {
  name: 'Susan',
  score: 86
 },
 {
  name: 'Abel',
  score: 86
 },
 {
  name: 'Kevin',
  score: 86
 }
];

obj.sort((a,b) => {
  if(b.score - a.score === 0){
    if(a.name < b.name) return -1;
    if(a.name > b.name) return 1;
    return 0;
  }
  else{
     return b.score - a.score;
  }
});

console.log(obj);
Hriday Modi
  • 2,001
  • 15
  • 22