Array flatMap()
JavaScript Array flatMap () Definition:
The flatMap () method maps each value to a new value, and then returns the resulting array to a maximum depth of 1. To be more specific, for example, a series called [1, 2]. Let’s set this sequence to a function that will multiply each element by 2. Let’s apply the flatMap () method to the function that we match. This is our new series: [2, 4].
Let’s see if we can encode the above example?
let list = [1, 2]
let arr = list.flatMap(x =>[x * 2])
console.log(arr)
[ 2 , 4 ]
Another advantage of using this method is that it shortens the codes. This method is a combination of the flat () and map () methods. This way we will do the same work with less code.
flat(): The flat() method available on the Array prototype returns a new array that’s a flattened version of the array it was called on. For more information about flat () please click here.
JavaScript Array flatMap() Syntax:
var new_array = arr.flatMap(function callback(currentValue[, index[, array]]) {
// return element for new_array
}[, thisArg])
callback:
Function that produces an element of the new Array, taking three arguments:
currentValue:
The current element being processed in the array.
indexOptional:
The index of the current element being processed in the array.
arrayOptional:
The array map was called upon.
thisArgOptional:
Value to use as this when executing callback.
JavaScript Array flatMap() Examples
Example 1
let list = [1, 2, 3, 4, 5]
let result = list.flatMap(x =>[x * 10]);
console.log(result)
output:
[10, 20, 30, 40, 50]
Example 2
let list = [1, 2, 3, 4, 5]
let result = list.flatMap(x =>[[x * 10]]);
console.log(result)
output:
[Array(1), Array(1), Array(1), Array(1), Array(1)]
0: [10]
1: [20]
2: [30]
3: [40]
4: [50]
Example 3
let list1 = ["john", "barry", "oliver"];
let list2 = ["rihanna", "jessica", "lisa"];
let combine = list1.flatMap((name, index) =>[name, list2[index]]);
console.log(combine)
output:
[“john”, “rihanna”, “barry”, “jessica”, “oliver”, “lisa”]
Example 4
let arr = ["javascript", "flatmap()"];
console.log(arr.flatMap(x => x.split("")));
console.log(arr.flatMap(x => x.split(" ")));
output:
[“j”, “a”, “v”, “a”, “s”, “c”, “r”, “i”, “p”, “t”, “f”, “l”, “a”, “t”, “m”, “a”, “p”, “(“, “)”]
[“javascript”, “flatmap()”]
Browser Support
Chrome | 69 |
Edge | no |
Firefox | 62 |
Internet Explorer | No |
Opera | 56 |
Safari | 12 |
Android webview | 69 |
Chrome for Android | 69 |
Edge mobile | no |
Firefox for Android | 62 |
Opera Android | 56 |
Thank You
LikeLiked by 1 person
Youre welcome 🙂
LikeLiked by 1 person