JavaScript Array flatMap() Method (original) (raw)

Last Updated : 12 Jul, 2024

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:

**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.

javascript `

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. TheflatMap()** method then flattens these arrays into a single-dimensional array of words.

javascript `

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.

**Supported Browser: