offline version v3


103 of 264 menu

map method

The map method allows you to apply a given function to each array element. In this case, the method does not modify the original array, but returns the modified one.

The method in the parameter receives a function that will be executed for each element of the array. The result of this function returned via return for an array element will become the new value of that element (see examples).

You can pass 3 parameters to the function. If these parameters are present (they are not required), then the first one will automatically get the array element, the second one will get its number in the array (index), and the third one will get the array itself.

Syntax

let new array = array.map(function(element, index, array) { some code return modified element; });

Example

We create an array, each element of which is twice the size of the corresponding element of the initial array:

let arr = [1, 2, 3, 4, 5]; let res = arr.map(function(elem) { return elem * 2; }); console.log(res);

The code execution result:

[2, 4, 6, 8, 10]

Example

Let's create an array, each element of which is obtained like this - the value of the element is multiplied by its index in the array:

let arr = [1, 2, 3, 4, 5]; let res = arr.map(function(elem, index) { return elem * index; }); console.log(res);

The code execution result:

[0, 2, 6, 12, 20]

Example

If necessary, the array itself can be passed to the third parameter:

let arr = [1, 2, 3, 4, 5]; let res = arr.map(function(elem, index, arr) { array arr will be available here });

Example

The map method can also be used to iterate over multidimensional arrays. Let, for example, given an array like this:

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

Let's iterate over this array through map and output its elements to the console:

let arr = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]; let result = arr.map(function(elem) { console.log(elem); });

As a result, console.log will output [1, 2, 3], then [4, 5, 6], then [7, 8, 9].

As you can see, subarrays get into the variable elem. Let's now apply the map method to each subarray and square each of its elements:

let arr = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]; let result = arr.map(function(elem) { return elem.map(function(num) { return num * num; }); }); console.log(result);

See also

  • the forEach method
    that applies a function for each array element
  • the filter method
    that allows you to filter the elements of an array
  • the some and every methods
    that perform an array check
  • the reduce and reduceRight methods
    that reduce an array to a single value
enru