Lets dig a little deeper into how the Array .map()
method works so we can get a more intuitive grasp on when and how to use it. We will be creating our own version of Array .map
to help show exactly what is going on inside. This is an interpretation of how .map
works not how it exactly works, see mdn for more details.
// Instead of adding to the Array prototype // we can just make an function that takes two args // data - [array] - the array to use during the mapping // cb - the callback function to call on each item in the data array const customMap = (data, cb) => { // create an array to fill with mapped values const mappedData = [] // loop over each item in the data array for (let item of data) { // execute the callback and pass in the current item value const fromCB = cb(item) // the returned value gets pushed into the mappedData array mappedData.push(fromCB) } // Finally we return the mapped values without mutating the original data return mappedData }
This is the basics of what the Array .map
method does. You give it an array and a callback. The callback is executed on each item in the array. The value that is returned from the callback value are then added to a new array in the same order as it is traversed. And finally once looping through the full array, we return the new mapped array.
Here are some example usages:
const customMap = (data, cb) => { const mappedData = [] for (let item of data) { const fromCB = cb(item) mappedData.push(fromCB) } return mappedData } const sampleData = [1, 2, 3, 4, 5] const timesTwo = customMap(sampleData, (item) => item * 2) console.log(timesTwo) // timesTwo : [2, 4, 6, 8, 10] const appendHello = customMap(sampleData, (item) => ("hello" + item)) console.log(appendHello) // appendHello : ['hello 1', 'hello 2', 'hello 3', 'hello 4', 'hello 5']
Console:
Hopefully this helped illuminate how the Array map method works a bit more. It is a very powerful tool and is especially easy to use. Now get out there and map even more data!