Underscore.js each() function

Underscore.js _.each()

Underscore each function is used to iterate over a list of elements.

The full function signature is _.each(list, iteratee, [context]).

The second function parameter “iteratee” is a function and will be called against each item of the iterated list object or array passed as its first argument.

Each invocation of iteratee is called with three arguments: (element, index, list)
 
For example,

<!DOCTYPE html>
<html>
    <head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore.js"></script>
        
        <script type="text/javascript">
            var employees = ["Andy","Bob","Charlie"];
            _.each(employees,function(name,index){
                console.log("Employee " + name + " is present at index " + index);
            });
        </script>
    </head>
    
</html>

Output :

underscore each
 
Similarly, we can iterate over an array of objects in following manner :

<!DOCTYPE html>
<html>
    <head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore.js"></script>
        
        <script type="text/javascript">
            var employees = [{name:"Andy", age:21},
                             {name:"Bob", age:31},
                             {name:"Charlie", age:41}];
            
            _.each(employees,function(value,key){
                console.log("Name: " + value.name + " , Age: " + value.age);
            });
        </script>
    </head>
    
</html>

Output :

underscore.js each function
 

© 2016, https:. All rights reserved. On republishing this post, you must provide link to original post

Leave a Reply.. code can be added in <code> </code> tags