ES10 - Array FlatMap

This tutorial covers Array class methods flat and FlatMap introduced ES2019 includes examples..

ES10 feature - Array prototype methods

ES10 introduced two methods to Array class to JavaScript.

  • Array.prototype.flat
  • Array.prototype.flatMap

flatten array

flat method is used to return new array with all sub array concatenated recursively with given depth Originally it was proposed as array.prototype.flatten() method.

syntax

array.flat(depth)

Parameters and returns

  • depth tell how much given depth to make flatten array for a given nested sub array. Default is 1.
  • Returns new flatten array

Here is array flat example

let arrayStringNumbers = ["one",
["two","three", "four", ["five", "six", ["seven", "eight", "nine", "ten"]]]
];
console.log(arrayStringNumbers.flat())
//["one", "two", "three", "four", ["five", "six", ["seven", "eight", "nine", "ten"]]]

console.log(arrayStringNumbers.flat(1));
//["one", "two", "three", "four", ["five", "six", ["seven", "eight", "nine", "ten"]]]

console.log(arrayStringNumbers.flat(2));
//["one", "two", "three", "four", "five", "six", ["seven", "eight", "nine", "ten"]]

console.log(arrayStringNumbers.flat(3));
["one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten"]

Array.prototype.flatMap method

flatMap method is combination of flat and map functionality for a given array, output is single flatten array. It will executes the mapping function for each element of an array, flattens the output into new array. It is equal to map() + flat() with depth =1 Syntax Array.flatMap(function call back) Parameters and returns

  • callback function logic
  • return type is new array with flatten array

Here is flatmap array example

let  arrayNumber= [1, 2, 3, 4];
console.log(arrayNumber.map(number => [number * 3])); 
//[[3], [6], [9], [12]]
console.log(arrayNumber.flatMap(number => [number * 3]));
// [3, 6, 9, 12]

let stringArray = ["es10", "", "feature"];
console.log(stringArray.map(word =>word.split(" "))); 
//[["es10"], [""], ["feature"]]
console.log(stringArray.flatMap(word =>word.split("")));
//["e", "s", "1", "0", "f", "e", "a", "t", "u", "r", "e"]