The _.each
function accepts an array or an object, an iteratee function and an optional context
object, the iteratee function is invoked once and in order for each array item
The iteratee function provides 3 arguments
item - The current iterated object (or value if an object was passed)
i - The index of the iterated object (or key if an object was passed)
list - A reference to the original array/list (the object that was passed)
Example 1:
_.each(["hello", "underscore"], function(item, i, list) {
alert(item)
});
The above example will show 2 alerts, the first with the words "hello" and the second for "world".
Example 2:
_.each({one: 1, two: 2, three: 3}, (value, key, object) =>
console.log(JSON.stringify(object));
);
This example will log a stringified version of the object 3 times.
.each
is a terminal operation, and unlike other intermediate functions (map, pluck, values etc..) you don't need to return inside the iteratee function body.