Skip to main content

JavaScript Array flatMap Method (Live Playground)

The JavaScript Array flatMap method is used to map each element using a mapping function, then flattens the result into a new array. It's essentially the same as running a map method and then a flat method.

Here's a basic example of how to use the flatMap method:

let numbers = [1, 2, 3];
let result = numbers.flatMap(x => [x, x * 2]);


// Expected output:
// [1, 2, 2, 4, 3, 6]

In this example, for each element in the numbers array, flatMap generates a new array [x, x * 2] (where x is the current element), then flattens these arrays into the result array.

Live Playground, Try it Yourself

Please note that flatMap only flattens one level deep:

let nestedNumbers = [1, 2, [3, 4]];
let result = nestedNumbers.flatMap(x => [x]);


// Expected output:
// [1, 2, [3, 4]]

In the second example, nestedNumbers.flatMap(x => [x]) doesn't flatten the nested array [3, 4] because it only flattens one level deep.

Live Playground, Try it Yourself

The flatMap method can be really handy when you need to perform a map operation and also flatten the result in one go.