Wednesday, March 14, 2018

What is the use of map function in Javascript?

The map() method is used to apply a function on every element in an array. A new array is then returned.

Here’s what the syntax looks like:


let newArr = oldArr.map((val, index, arr) => {
  // return element to new Array
});


newArr — the new array that is returned
oldArr — the array to run the map function on
val — the current value being processed
index — the current index of the value being processed
arr — the original array

You do have to remember to include a return statement in your callback. If you don't, you'll get a new array filled with undefined. 

Let see what is internal coding of map

var map = function (array, callback) {

    var new_array = [];

    array.forEach(function (element, index, array) {
//You can modify element here
       new_array.push(callback(element)); 
    });

    return new_array;

};

var task_names = map(tasks, function (task) {

    return task.name;


});

Source : https://code.tutsplus.com/tutorials/how-to-use-map-filter-reduce-in-javascript--cms-26209

No comments:

Followers

Link