Array.flatMap() - for applying a map and a flat on an array
Dillion Megida
Posted on April 22, 2022
This article is the seventh of the Array Method Series. In this article, I will explain the flatMap
Array method.
What is the FlatMap Method?
The flatMap
method of arrays is a higher-order function that applies a map
and a flat
on an array. That is, .map().flat()
.
An array map
method is used for for mapping items in an array, while an array flat method is used for flatting nested arrays within an array
The flatMap
method maps each item in an array and flattens the final array by one depth level.
This method does not modify the array.
Syntax of the Some Method
array.flatMap(function(item, index, array){
// do some things on the item
// return an array or item
})
// the final array will be flattened
// by 1 depth
The callbackFunction
passed to the flatMap
method is applied to each item in the array during the loop, and the final array after the loop is flattened by one depth level.
The arguments passed to the callback function in each loop are the item
, the index
of the item, and the original array
.
Before I show you how to use the flatMap
method, let me first show you how to achieve the function of this method by using a map
and a flat
.
Without the FlatMap Method
The flatMap
method is an abstracted function that maps through an array and flattens the result. Here's how to do without this method:
const array = [1, 2, 3, 4]
// the mapping
const newArray = array.map(item => {
return [item, item*2]
})
console.log(newArray)
// [ [ 1, 2 ], [ 2, 4 ], [ 3, 6 ], [ 4, 8 ] ]
// the flattening
const flattenedArray = newArray.flat()
console.log(flattenedArray)
// [1, 2, 2, 4, 3, 6, 4, 8]
This code is similar to what the flatMap
method does in the background. The map
method loops through each item and returns a value for the final array. The flat method loops through recursively and flattens the final array by one depth level.
With the FlatMap Method
Here's how you achieve the previous result with flatMap
:
const array = [1, 2, 3, 4]
const newArray = flatMap(item => {
return [item, item*2]
})
console.log(newArray)
// [1, 2, 2, 4, 3, 6, 4, 8]
More straightforward. The difference between the flat in flatMap
and the flat in flat
is that the former does not allow you to specify a depth, while the latter allows you to. flatMap
only does flattening for a depth of one level.
You may be wondering what the difference is between using a map and a flat (map().flat()
) and using flatMap
. Well, apart from the fact that flatMap
is lesser lines of code and is more concise, it is slightly more efficient than doing two loops (calling map
and flat
separately, according to MDN)
Posted on April 22, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 30, 2024