-1

if an object array has the following attributes type, age and gender eg

[{type: 0, age: 15, gender: "male"}, 
{type: 0, age: 16, gender: "female"}, 
{type: 0, age: 17, gender: "male"}]

what is the best way to do a filter and sort such that the object with the highest age (sort part) with type = 0 and gender= male (filter part) will be returned (in this instance {type: 0, age: 17, gender: "male"})

so it first have to do a filter by type = 0 and gender = male then do a sort to get the highest age for all objects that fit the criteria

3
  • what do you mean by sort? Commented May 23, 2017 at 12:27
  • sort based on age? Commented May 23, 2017 at 12:27
  • 4
    what is the best way to do a filter and sort? array.filter and array.sort Commented May 23, 2017 at 12:28

2 Answers 2

4

Assuming, you want the oldest male with type equals zero, you could filter first and the sort by age descending. Take the first object as result.

var array = [{type: 0, age: 15, gender: "male"}, {type: 0, age: 16, gender: "female"}, {type: 0, age: 17, gender: "male"}],
    result = array.filter(function (a) {
        return a.type === 0 && a.gender === 'male';
    });

result.sort(function (a, b) { return b.age - a.age; });
console.log(result[0]);

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

Comments

0

Assuming that you want the object with type=0 and max age, you do not need to filter or sort.

Just loop through list and check if type is 0, then compare age and return the one with max

Note: This is only applicable if you want to fetch one item. It can be scaled for few finite elements but not for generic number

var array = [{type: 0, age: 15, gender: "male"}, {type: 0, age: 16, gender: "female"}, {type: 0, age: 17, gender: "male"}],
  result = array.reduce(function (p,c) {
    if(p.type === 0 && c.type === 0){
      return p.age > c.age ? p : c;
    }
    return p;
  });
console.log(result);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.