Node js sortBy() based on multiple attributes using Underscore

How to sort an array with objects based on multiple attributes

The first property “primaryScore” is same between the two objects. The two “primaryScore” is equal to 75. So the second property I am going to use to compare the three objects is “secondaryScore”. consider the following array:
var persons = [
{name: 'John', primaryScore: 75, secondaryScore: 60},
{name: 'Sansa', primaryScore: 75, secondaryScore: 50},
{name: 'Arya', primaryScore: 80, secondaryScore: 60},
{name: 'Sam', primaryScore: 80, secondaryScore: 50}
];

In the first sortBy function it sorts the secondary score, when the second sortBy function finds that John and Sansa have the same primary score it will keep them in the order it found them, which the first sortBy set to “Sansa, John”.

var sortedArray = _(persons).chain().sortBy(function(person) {
return person.secondaryScore;
}).sortBy(function(person) {
return person.primaryScore;
}).value();

In the first sortBy function it sorts the secondary score, when the second sortBy function finds that John and Sansa have the same primary score it will keep them in the order it found them, which the first sortBy set to “Sansa, John”.

The Sorted Array is now:

sortedArray = [
{name: 'Sansa', primaryScore: 75, secondaryScore: 50},
{name: 'John', primaryScore: 75, secondaryScore: 60},
{name: 'Sam', primaryScore: 80, secondaryScore: 50},
{name: 'Arya', primaryScore: 80, secondaryScore: 60}
];

This gives you array in ascending order. if You want the array in descending order, Then use the reverse(). like this:
var descSortedArray = sortedArray.reverse();

 

Leave a Reply

Your email address will not be published. Required fields are marked *