The map() method generates a new array by applying a function to each element within the original array.
It does not execute the function for array elements lacking values, and it does not alter the original array.
In the following example, each value within the array is multiplied by 2:
Example
const numbers1 = [45, 4, 9, 16, 25]; const numbers2 = numbers1.map(myFunction); function myFunction(value, index, array) { return value * 2; } |
Keep in mind that the callback function accepts three arguments:
When a callback function utilizes only the value parameter, you can omit the index and array parameters.
Example
const numbers1 = [45, 4, 9, 16, 25]; const numbers2 = numbers1.map(myFunction); function myFunction(value) { return value * 2; } |
Introduced in ES2019, the Array flatMap() method in JavaScript initially maps all elements of an array and subsequently generates a new array by flattening it.
Example
const myArr = [1, 2, 3, 4, 5, 6]; const newArr = myArr.flatMap((x) => x * 2); |
JavaScript Array flatMap() is compatible with all modern browsers, with support extending back to January 2020.
The filter() method generates a new array comprising elements from the original array that satisfy a given test.
In this example, a new array is created containing elements with values greater than 18:
Example
const numbers = [45, 4, 9, 16, 25]; const over18 = numbers.filter(myFunction); function myFunction(value, index, array) { return value > 18; } |
It’s important to note that the callback function accepts three arguments:
In the provided example, since the callback function doesn’t utilize the index and array parameters, they can be excluded:
Example
const numbers = [45, 4, 9, 16, 25]; const over18 = numbers.filter(myFunction); function myFunction(value) { return value > 18; } |