Roy Eun
Roy Eun

Reputation: 1

reduce more than one value

Is there any way that I can return more than one object with the reduce function? For example, I want to return the oldest age and I have 3 people who are all the same age. See below, thanks!

var dataArray = [
     {name: "Roy", age: 24, sex: "M"},
     {name: "Ben", age: 25, sex: "M"},
     {name: "Jamie", age: 23, sex: "F"},
     {name: "David", age: 25, sex: "M"},
     {name: "Bob", age: 25, sex: "M"}
 ];

 var oldestPeople = dataArray.reduce(function(max, cur) {
     console.log("Max is " + max["name"]);
     console.log("Cur is " + cur["name"]);
     if (cur["age"] === max["age"]) {
         return [max, cur];
     } else if (cur["age"] > max["age"]) {
         return cur;
     } else {
         return max;
     }
 });

I am able to get it to return two objects, but my max becomes undefined once [max, cur] is returned. Thanks again!

Upvotes: 0

Views: 357

Answers (2)

Oriol
Oriol

Reputation: 288080

If you want to use reduce, you could use something like

var oldestPeople = dataArray.reduce(function(max, cur) {
  if (cur.age === max.age) {
    max.people.push(cur);
  } else if (cur.age > max.age) {
    max.age = cur.age;
    max.people = [cur];
  }
  return max;
}, {age: -Infinity, people: []}).people;

But maybe I would prefer a forEach:

var maxAge = -Infinity,
    oldestPeople = [];
dataArray.forEach(function(cur) {
  if (cur.age === maxAge) {
    oldestPeople.push(cur);
  } else if (cur.age > maxAge) {
    maxAge = cur.age;
    oldestPeople = [cur];
  }
});

Upvotes: 0

Soren
Soren

Reputation: 14688

Looking at the documentation https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

then the first callback it the return value from the previous invocation of the callback.

So the problem you are having is that sometimes you return and array [max,cut] and other times you return a single value cur or max -- just stick to always return an array and you should be fine, like

 if (max)
    console.log("Max is " + max[0]["name"]);
 else
    return [cur];
 console.log("Cur is " + cur["name"]);
 if (cur["age"] === max[0]["age"]) {
     return max.concat([cur]);
 } else if (cur["age"] > max[0]["age"]) {
     return [cur].concat(max);
 } else {
     return max.concat([cur]);
 }

Upvotes: 1

Related Questions