JavaScript(JS) array method - map
The map()
method in JavaScript is used to create a new array by applying a function to each element of the original array. The function takes the current element as an argument and returns a new value for that element. The map()
method returns an array of the same length as the original array, with each element being the result of the function applied to the corresponding element in the original array.
Here's an example of how to use the map()
method:
let numbers = [1, 2, 3, 4, 5]; let doubledNumbers = numbers.map(function(number) { return number * 2; }); console.log(doubledNumbers); // [2, 4, 6, 8, 10]Source:w.wwtheitroad.com
In this example, we have an array numbers
containing the elements [1, 2, 3, 4, 5]
. We use the map()
method to create a new array doubledNumbers
by doubling each element of the numbers
array. The function passed to map()
takes each element of the numbers
array as an argument and returns that element multiplied by 2. The map()
method returns an array of the same length as the numbers
array, with each element being the result of the function applied to the corresponding element in the numbers
array.
Note that the map()
method does not modify the original array, but creates a new array instead.