JavaScript Array flatMap() Method
The flatMap() method transforms each element of an array using a mapping function and flattens the result into a new array. It applies the function to every element, avoiding empty ones, and preserves the original array.
Syntax:
let A = array.flatMap(function callback(current_value, index, Array)) {
// It returns the new array's elements.
}
Parameters:
- current_value: It is the input array element.
- index:
- It is optional.
- It is the index of the input element.
- Array:
- It is optional.
- It is used when an array map is called.
Return Values:
It returns a new array whose elements are the return value of the callback function.
Example 1: In this example the flatMap() method doubles and squares each number in the array, creating a new flattened array, making complex transformations manageable.
const numbers = [1, 2, 3, 4];
const doubledAndSquared =
numbers.flatMap(num => [num * 2, num ** 2]);
console.log(doubledAndSquared);
Output
[ 2, 1, 4, 4, 6, 9, 8, 16 ]
Example 2: In this example, the flatMap()
method is employed to process an array of sentences. The callback function, sentence => sentence.split(' ')
, is applied to each sentence, splitting it into an array of words. The flatMap()
method then flattens these arrays into a single-dimensional array of words.
const sentences =
["Hello world", "How are you?", "JavaScript is fun"];
const words =
sentences.flatMap(sentence => sentence.split(' '));
console.log(words);
Output
[ 'Hello', 'world', 'How', 'are', 'you?', 'JavaScript', 'is', 'fun' ]
We have a complete list of Javascript Array methods, to check those please go through this Javascript Array Complete reference article.