How to Map Array Elements in JavaScript

To map an array of elements in JavaScript, use the array.map() function. The array.map() is a built-in JavaScript pure function that creates a new array populated with the results of calling a provided function on every item in the calling array.

The map() function creates a new array by calling a function for every array element. The map() does not execute the function of every item. The map() does not change an original array, and that’s why it is a pure function.

Syntax

array.map(function(current value, index, array), this value)

Arguments

  1. function(): It is a function to be run for each array element.
  2. current value: It is a value of the current element.
  3. index: It is an index of the current element.
  4. array: The array for the current element.
  5. this value: A value passed to the function to be used as its value.

Return value

          It is an array resulting from a function for each array element.

          Example

          const num = [10, 20, 30, 40, 50]
          const newarr = num.map(myfun)
          
          function myfun(n) {
           return n * 10;
          }
          
          console.log(newarr);

          Output

          [ 100, 200, 300, 400, 500 ]

          In this example, you can see that we are multiplying each element by 10 using the array.map() function. The map() function calls a provided CALLBACK FUNCTION once for each item in an array, in order, and constructs a new array from the results.

          That’s it for this tutorial.

          See also

          How to flatten Array of Objects in JavaScript

          How to read an array of objects in JavaScript

          How to combine arrays in JavaScript

          Leave a Comment