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.
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.
Share Improve this question asked Sep 12, 2015 at 13:41 musubimusubi 1,2683 gold badges14 silver badges22 bronze badges 03 Answers
Reset to default 10Sounds 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 prehensions:
let newArray = [for (person of people)
if (calculateAge(person.birthDate) > 50)
{ person: person, age: calculateAge(person.birthDate) }
];
Update: List prehensions 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/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator)
This could work for you:
var sorted = _.filter(people, function(person) {
var age = calculateAge(person.birthDate);
if (age > 50) {
return true;
}
});
var newArray = _.map(sorted, function(person) {
var age = calculateAge(person.birthDate);
return {person: person, age: age};
});
This will first filter the list and then return a new array with the objects of the people whos age is above 50.
Try this:
people = _.pluck(
_.filter(
_.map(people, function(person) {
return { person: person, age: calculateAge(person.birthDate) };
}),
function(person) {
return person.age > 50;
}
),
"person"
);
See working fiddle