JavaScript Array flatMap

Created with Sketch.

JavaScript Array flatMap

Summary: in this tutorial, you’ll about the JavaScript Array flatMap() method that maps each element in an array using a mapping function and flattens the result into a new array.

Introduction to JavaScript Array flatMap() method

The flat() method creates a new array with the elements of the subarrays concatenated into it.

The map() method creates a new array whose elements are the results of a mapping function.

The flatMap() method is the combination of the map() method followed by the flat() method of depth 1.

The flatMap() method first maps each element in an array using a mapping function and then flattens the results into a new array.

The following shows the syntax of the flatMap() method:

let newArray = arrayObject.flatMap(callback,thisArg);

Code language: JavaScript (javascript)

The flatMap() method takes two parameters:

1) The callback mapping function

The callback is the mapping function has the same syntax as the one in the map() method:

function callback(currentValue [[,index], array]);

Code language: JavaScript (javascript)

2) The thisArg argument

The optional thisArg argument is a value to use as this when executing the callback.

Note that the flatMap() method doesn’t modify the original array.

JavaScript Array flatMap() examples

Let’s take some examples of using the flatMap() method.

1) Creating words from sentences example

Suppose that you have the following array:

let sentences = ["JavaScript Array flatMap()", " ", "is", " ", "Awesome"];

Code language: JavaScript (javascript)

The following map() function splits the words of  sentences:

let words = sentences.map(s => s.split(' '));
console.log(words);

Code language: JavaScript (javascript)

Output:

[
[ 'JavaScript', 'Array', 'flatMap()' ],
[ ' ' ],
[ 'is' ],
[ ' ' ],
[ 'Awesome' ]
]

Code language: JavaScript (javascript)

The result is an array of nested arrays filled by words. To flatten the result, you can use the flat() method on the result of the map() method. However, it’ll be more concise to use the flatMap() method.

The flatMap() creates a flattened array by running each sentence in the array through a mapping function and flattening the mapped results:

let sentences = [
"JavaScript Array flatMap()",
" ",
"is",
" ",
"Awesome"
];

let words = sentences.flatMap(s => s.split(' '));
console.log(words);

Code language: JavaScript (javascript)

Output:

[ 'JavaScript', 'Array', 'flatMap()', '', '', 'is', '', '', 'Awesome' ]

Code language: JSON / JSON with Comments (json)

2) Adding and removing elements during mapping example

The flatMap() method allows you to add or remove elements during mapping. Consider the following example:

Suppose that you have the following shopping cart:

let cart = [{
name: 'Smartphone',
qty: 2,
price: 500,
freeOfCharge: false
},
{
name: 'Tablet',
qty: 1,
price: 800,
freeOfCharge: false
}
];

Code language: JavaScript (javascript)

If customers buy a smartphone, you want to give them a free screen protector.

When the customer adds a smartphone to the cart, you can add a screen protector to the cart using the flatMap() method as follows:

let newCart = cart.flatMap(
(item) => {
if (item.name === 'Smartphone') {
return [item, {
name: 'Screen Protector',
qty: item.qty,
price: 5,
freeOfCharge: true
}]
} else {
return [item];
}
}
);

console.log(newCart);

Code language: JavaScript (javascript)

The cart will look like this:

[
{ name: 'Smartphone', qty: 2, price: 500, freeOfCharge: false },
{ name: 'Screen Protector', qty: 2, price: 5, freeOfCharge: true },
{ name: 'Tablet', qty: 1, price: 800, freeOfCharge: false }
]

Code language: JavaScript (javascript)

The following uses the reduce() method to calculate the total amount from the items in the cart. It ignores the free-of-charge items, like screen protectors:

const total = newCart.reduce((sum, item) => {
if (!item.freeOfCharge)
sum += item.price * item.qty;
return sum;
}, 0);

console.log({total});

Code language: JavaScript (javascript)

Output:

{ total: 1800 }

Code language: JavaScript (javascript)

Summary

  • Use the flatMap() method to create a flattened array of elements by running each element in the collection through a mapping function and flattening the mapped results.

Leave a Reply

Your email address will not be published. Required fields are marked *