hackermann hackermann - 4 months ago 13
Javascript Question

How do I build a contains function using reduce instead of a for loop in JavaScript?

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

Answer

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.

Comments