DS_ DS_ - 1 month ago 9
Javascript Question

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?


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

With same age, the difference is zero (a falsey 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;

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