Underscore.js _.map() Function
Parameters: It accepts two parameters which are specified below-
- list: It is the list which contains some elements.
- function: It is the function which is executed by taking each element of the list.
Return values: It returns the object property value or array element value at the current position.Passing a list of numbers with user defined function: When we are passing the list of elements to the user defined function then it takes the element from the list one by one and performs the operations of the function. Here, the function calculates the multiplication operation. It multiplies the list elements by 2. After performing its operations, the function then returns the value to be shown on the console.
Output:Passing a list of numbers with another user defined function: When we are passing the list of numbers to the user defined function which takes ‘num’ as argument then it takes the numbers from the list one by one and performs it’s operation. The function used here takes each element from the list and uses it in the resulted sentence. Therefore, the final result is a sentence “This is **(element of the list) list item”.
Output:Passing a list of numbers with _.last inbuilt function: When we are passing the list of numbers to the _.last inbuilt function then it takes the words from the list one by one and performs it’s operation. The _.last() takes each array from the list and returns the last element from each array. Therefore, the final result is the last element of every array.
Output:Passing a list of words with a user defined function: First we need to create a list which we will be going to use. Here the function takes each word from the list and prints it to the console along with a set of words which are “is mapped from a list”. The output will contain the list item along with the given set of words.
Output:Passing a list of numbers with a : ? function: Pass the list items to the function directly. Here the function uses : ? operators (instead of for loop) to find whether the list number is smaller than or greater than 3 accordingly it prints the result.