ES10 feature - Array prototype methods

ES10 introduced two methods to Array class to JavaScript.

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

flatten array

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

syntax

array.flat(depth)

Parameters and returns

  • depth tells how much-given depth is to make a flattened array for a given nested subarray. Default is 1.
  • Returns a new flattened 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

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

  • callback function logic
  • the return type is a new array with a flattened 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"]