Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 610
hackermann Avatar asked Oct 20 '15 17:10

hackermann


People also ask

Is reduce better than for loop?

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.

What is reduce () in JavaScript?

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 )

How do you use reduce in JS?

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.

What is accumulator in reduce JavaScript?

accumulator is the value returned from the previous iteration. It will be initialValue for the first iteration.


1 Answers

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.

like image 93
Simon H Avatar answered Sep 30 '22 04:09

Simon H