JavaScript Glossary: Array .map() Method
Publikováno: 8.2.2019
Basics
The map()
method takes a callback method that performs an operation on the elements in the array. It returns a new array containing the resulting values of running the ...
Basics
The map()
method takes a callback method that performs an operation on the elements in the array. It returns a new array containing the resulting values of running the operation on each element. This method does not mutate the calling array.
let newArray = [1, 2, 3, 4, 5].map(function(number){
return number * 2
})
// [2, 4, 6, 8, 10]
https://scotch.io/embed/gist/e8e919a60abe7a6627b2f81365433b95
The .map()
method:
- Takes a callback function that is called once for each element.
- Calls the callback function and gets the result of the operation run on the element
- Returns a new array with the results> The .map() method creates a new array and doesn't mutate the old array.
Syntax
let newArray = oldArray.map(callback(element[, index[, array]])[, thisArg])
2 Parameters
callback This is the function that executes each of the elements of the array. The callback function is required and can take three parameters:
element
: This is the element currently being executed -required
.index
: This is the index of the current item -optional
.array
: This is the array that is currently being processed -optional
.
thisArg
This is an argument passed to be used as the this
value in the callback
- optional
Returns an array
A new array with each value being the result of the callback function.
const numbers = [2, 4, 6, 8];
const squares = numbers.map(number => number * numbers);
console.log(squares);
// output: Array [4, 16, 36, 64]
Common Uses and Snippets
Creating a new array from the values contained in a calling array.
https://scotch.io/embed/gist/f7d497b5c6d5c6f36b4d70eb069c6b6a
Reformatting the values contained within an array
https://scotch.io/embed/gist/0cbce5fb6c634888d09ad08eaf531759