Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Underscore's similar functions: _.contains vs. _.some and _.map vs _.each

Is there a reason to use one over the other? It seems that _.some and _.map are easier to use or applicable to more situations (from my very limited experience) but from reading it, they sound as if they should do the same thing. I'm sure there are other instances of this and I'm all ears on learning some of the comparisons.

like image 699
rashadb Avatar asked Dec 08 '22 04:12

rashadb


1 Answers

_.contains vs _.some

_.contains (_.contains(list, value, [fromIndex])

Returns true if the value is present in the list. Uses indexOf internally, if list is an Array. Use fromIndex to start your search at a given index.

_.some (_.some(list, [predicate], [context]))

Returns true if any of the values in the list pass the predicate truth test. Short-circuits and stops traversing the list if a true element is found.

The main difference between _.some and _.contains is that, contains checks if a given item is present in the given list and some checks if any of the elements in the list satisfies the predicate passed. So, they both are doing different tasks.

_.each vs _.map

_.each (_.each(list, iteratee, [context])

Iterates over a list of elements, yielding each in turn to an iteratee function.

_.map (_.map(list, iteratee, [context])

Produces a new array of values by mapping each value in list through a transformation function (iteratee).

_.map calls the function passed (iteratee) with each and every element of the list to create a new Array object, but _.each simply calls the function passed (iteratee) with each and every element (Note: this doesn't create an Array).

Basically _.each is the functional equivalent of for (var i = 0; i < array.length; i += 1) {...}. Again, they both are doing different jobs.

like image 102
thefourtheye Avatar answered Mar 16 '23 14:03

thefourtheye