I guess this is two questions. I am still having trouble with the reduce method, I get the simple way of using it
reduce([1,2,3], function(a, b) {
return a + b;
}, 0);
//6
Using it with anything other than numbers really confuses me. So how would I build a contains function using reduce in place of the for loop? Comments would be appreciated. Thank you all.
function contains(collection, target) {
for(var i=0; i < collection.length; i++){
if(collection[i] === target){
return true;
}
}
return false;
}
contains([1, 2, 3, 4, 5], 4);
//true
Writing that many code lines for just a simple sum must have a strong reason, so unless the performance is that critical, . reduce is much better. The tests again showed no difference between the loops.
reduce() method in JavaScript is used to reduce the array to a single value and executes a provided function for each value of the array (from left-to-right) and the return value of the function is stored in an accumulator. Syntax: array.reduce( function(total, currentValue, currentIndex, arr), initialValue )
JavaScript Array reduce()The reduce() method executes a reducer function for array element. The reduce() method returns a single value: the function's accumulated result. The reduce() method does not execute the function for empty array elements. The reduce() method does not change the original array.
accumulator is the value returned from the previous iteration. It will be initialValue for the first iteration.
This is what you need:
function contains(collection, target) {
return collection.reduce( function(acc, elem) {
return acc || elem == target;
}, false)
};
As adaneo says, there is probably an easier way for this particular question, but you tagged this 'functional programming' so I guess you want to get better at this way of tackling problems, which I totally endorse.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With