hackermann hackermann - 1 year ago 85
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);

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);

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download