I have an array of items on which I have to perform 2 tasks:
- Applying a function on the array item
- Checking if the value is true or false.
The functional approach to solving this would be
var result = arr.map(function(item){return some_action(item);}).filter(function(item){return other_action(item) == true;});
But here the array arr
is traversed twice in comparison to
var result = [];
arr.forEach(function(item){
var x = other_action(some_action(item));
if (x)
result.push(x);
});
Isn't the functional approach bad in this case or am I not using map
and filter
the right way?