flatMap method
The flatMap
method returns a
new array created after a callback
has been applied to each element of
the original array specified in the
method parameter. At first glance,
the flatMap
method is similar
to the map
method, but its
main difference is that it always
returns a one-dimensional array.
Syntax
let newArray = array.flatMap(function);
Example
Let's get a new array using
the flatMap
method:
let arr = ['a', 'b', 'c'];
let res = arr.flatMap(function(elem) {
return elem + '!';
});
console.log(res);
The code execution result:
['a!', 'b!', 'c!']
Example
Let's get a new array from the original one, consisting of numbers:
let arr = [1, 2, 3, 4, 5];
let res = arr.flatMap(function(elem) {
return elem + 2;
});
console.log(res);
The code execution result:
[3, 4, 5, 6, 7]
Example
Let's try to apply the flatMap
method to an array with the first
level of nesting:
let arr = [1, 2, 3, [4, 5]];
let res = arr.flatMap(function getElem(elem){
return elem + 2;
});
console.log(res);
After executing the code, we will see that the conditions of the function have been applied to the subarray, counting it as one element. Therefore, calling this method in nested arrays does not make sense:
[3, 4, 5, '4,52']
Example
If we want not to bother with a level
of nesting, but to merge the entire
array, then we use the parameter
Infinity
:
let arr = ['a', 'b', ['c', 'd', ['e', 'f', ['g', 'h', ['i']]]]];
let res = arr.flatMap(Infinity);
console.log(res);
The code execution result:
[
'a', 'b', 'c',
'd', 'e', 'f',
'g', 'h', 'i'
]
Example
Let's apply two methods to the array:
flatMap
and map
, and the
parameter of both methods will contain
a function that makes the array
two-dimensional:
let arr = [1, 2, 3, 4, 5, 6];
let res1 = arr.map(elem => [elem * 3]);
let res2 = arr.flatMap(elem => [elem * 3]);
console.log('map method', res1);
console.log('flatMap method', res2);
The code execution result:
'map method' [[3], [6], [9], [12], [15], [18]]
'flatMap method' [3, 6, 9, 12, 15, 18]
See also
-
the
flat
method
that returns an array of subarrays