JavaScript Array map()
method is used to transform an array of elements. The map() method creates an array by calling a specific function on each element present in the parent array.
array.map(function(currentValue, index, arr), thisValue)
Note: map()
does not execute the function for empty elements and does not change the original array.
JavaScript Array Map
A simple example code uses a for
loop to iterate over the elements, transform each individual one, and push the results into a new array.
<!DOCTYPE html>
<html>
<body>
<script >
const array1 = [1, 4, 9, 16];
const res = array1.map(x => x * 2);
console.log(res);
</script>
</body>
</html>
Output:
Return a new array with the square root of all element values:
<script>
const numbers = [4, 9, 16, 25];
const newArr = numbers.map(Math.sqrt)
console.log(newArr);//[ 2, 3, 4, 5 ]
</script>
Do comment if you have any doubts or suggestions on this JS method code.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version