Javascript Map

The map() method creates a new array with the results of calling a provided function on every element in the calling array

Suppose you have an array:

var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];

Now you want to find the square of each item in this array. So what you can do:

var anotherArr = []
for(var i = 0; i < arr.length; i++) {
anotherArr.push(arr[i] * arr[i])
}

Now you will get your desired result in anotherArr. But even if that is true, here we have a new array to look at. Again we have to use another method push. And there are a few other uses inside that are actually Meaningless. No matter the only thing you want to do in the middle of the map. The function you want to apply to each of your items first. Square of each item you want:

function getSquare(item) {
return item * item
}

Now you want to apply this function to every item in your array. This is where the map () comes in.

arr.map(getSquare)

Now we know that this also returns an array. Now where to store that array:

var newArr = arr.map(getSquare);

Now the whole thing can be written like this

var newArr = arr.map(function(item) {
return item * item;
})

This will give the same result as before. Now here we see that we have used an item as an argument. But here, map () accepts three arguments. The first argument is that it selects every item in the array, the second argument is the index number of the item in the array, and the third number will always return the whole array.

var newArr = arr.map(function(item, index, fullArr) {
console.log('Item: ' + item + ' and index: ' + index + '. Full Array: ' + fullArr)
})

And if you use ES6 syntax then see how it is:

  • Released On:
    03-10-2024
  • Tags:
    javascript, es6