Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lodash - Conditionally Return Object from a Map Method

I want to iterate through an array, run a calculation, and if the condition is true for the result, return a new object. _.filter(...) would not work here, since the iterator function must return either true or false.

_.map(people, function(person) {

    var age = calculateAge(person.birthDate);

    if (age > 50) {
        return {person: person, age: age};
    }

});

I've tried searching all over, including the documentation, but I haven't found a way to do this well.

like image 994
musubi Avatar asked Sep 12 '15 13:09

musubi


1 Answers

Sounds like maybe you want reduce and not map:

var newArray = _.reduce(people, function(results, person) {
  var age = calculateAge(person.birthDate);
  if (age > 50) {
     results.push({ person: person, age: age });
  }
  return results;
}, []);

Also if you are ES6+ and/or using Babel, this might be a good use for list comprehensions:

let newArray = [for (person of people)
                if (calculateAge(person.birthDate) > 50)
                { person: person, age: calculateAge(person.birthDate) }
               ];

Update: List comprehensions have been dropped from from Babel 6. The ES2015 version would look like:

const newArray = people.reduce((results, person) => {
  const age = calculateAge(person.birthDate);
  return (age > 50) ? [...results, { person, age }] : results;
}, []);

(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator)

like image 190
7zark7 Avatar answered Oct 16 '22 07:10

7zark7