In this article, you will learn about the javascript Array built-in method Array.prototype.flatMap(). How does this method work in javascript?
This Array.prototype.flatMap() method is a combination of map() and flat() methods. This method first maps each element in a given array using a mapping function and then flattens the array results into a new array.
array.flatMap(callback(element [, index [, array]]) [,thisParameter]);
This method takes 2 parameters as given below:
this to be used while executing the callback function.The flatMap() method does not change the original array. And the flatMap() method is equivalent to array.map().flat().
Here are some examples of Array.prototype.flatMap() method:
const arr1 = [0, 1, 2, [3, 4]];
console.log(arr1.flatMap(element => element))
//Output => [0, 1, 2, 3, 4]
const arr2 = [0, 1, 2, [3, 4, [5, 6]]];
console.log(arr2.flat(element => element))
//Output => [0, 1, 2, 3, 4, [5, 6]]
//Remove empty slots using flat() method
const arr3 = [1, 2, , 4, 5];
console.log(arr3.flatMap(element => element));
//Output => [1, 2, 4, 5]
const arr4 = [1, , 3, ["a", , "c"]];
console.log(arr4.flatMap(element => element));
//Output => [ 1, 3, "a", "c" ]
const arr5 = [1, , 3, ["a", , ["d", , "e"]]];
console.log(arr5.flatMap(element => element));
//Output => [ 1, 3, "a", ["d", empty, "e"] ]
I hope this article will help you to understand the javascript Array built-in method Array.prototype.flatMap().
Share your valuable feedback, please post your comment at the bottom of this article. Thank you!
Comments