Javascript Array flatMap()

Introduction

The array flatMap() method maps each element using a mapping function.

Then it flattens the result into a new array.

var new_array = arr.flatMap(function callback(currentValue[, index[, array]]) {
    
}[, thisArg]);
Parameter
Optional
Meaning
callback




Not




Mapping function
It takes three arguments:
currentValue - current element.
index - Optional, index of the current element.
array - Optional, the whole array.
thisArg
Optional
Value to use as this when executing callback.
let arr1 = [1, 2, 3, 4];
let a = arr1.map(x => [x * 2]); 
console.log(a);// [[2], [4], [6], [8]]
a = arr1.flatMap(x => [x * 2]);/*  ww  w. jav  a 2 s .  c o  m*/
console.log(a);// [2, 4, 6, 8]
// only one level is flattened
a = arr1.flatMap(x => [[x * 2]]);
console.log(a);// [[2], [4], [6], [8]]



PreviousNext

Related