1

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?

2
  • P.S. I've looked at a bunch of other posts and I really couldn't find a direct answer to this question. I know I'm new to actually posting here and I really did to my research and am not trying to create a duplicate question. Thank you! Commented Nov 28, 2016 at 22:11
  • You could use an if statement. Commented Nov 28, 2016 at 22:13

1 Answer 1

6

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; }

Sign up to request clarification or add additional context in comments.

4 Comments

So, the logical OR statement will run only if a.age == b.age? I believe you, but why?
because if a.age === b.age then the difference is zero and the other part with weight is evaluated.
@DS_ And also if a.age - b.age is NaN, e.g. some is not defined.
Makes sense to me and it works like a charm. Thank you so much!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.