DS_
DS_

Reputation: 113

Sort Objects in Array with duplicate values

So I've got an array of objects...

var array = [
    {'name':'Jack', 'age':'30', 'weight':'200'},
    {'name':'Ted', 'age':'27', 'weight':'180'},
    {'name':'Ed', 'age':'25', 'weight':'200'},
    {'name':'Bill', 'age':'30', 'weight':'250'}
]

...which I know I can sort in ascending order based on their age using...

array.sort(function(a, b) {
    return (a.age) - (b.age);
});

Given all this, how can sort by a second parameter only if the ages of two different objects are the same? For instance, in my object, both "array.name = Jack" and "array.name = Bill" have the same age of 30. How can I go in and make absolutely sure that Jack will come before Bill because Jack has a lower weight?

Upvotes: 1

Views: 2277

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386654

You could add another sort criteria with chaining with logical OR || operator.

With same age, the difference is zero (a falsy value) and the second part is evaluated.

This method allows to add more sort criteria.

var array = [{ name: 'Jack', age: '30', weight: '200' }, { name: 'Ted', age: '27', weight: '180' }, { name: 'Ed', age: '25', weight: '200' }, { name: 'Bill', age: '30', weight: '250' }];

array.sort(function (a, b) {
    return a.age - b.age || a.weight - b.weight;
});

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

Upvotes: 6

Related Questions