;

Javascript Array - flatMap() Method


Tutorialsrack 01/10/2022 Jquery Javascript

In this article, you will learn about the javascript Array built-in method Array.prototype.flatMap(). How does this method work in javascript? 

Array.prototype.flat()

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. 

Syntax
array.flatMap(callback(element [, index [, array]]) [,thisParameter]);

This method takes 2 parameters as given below:

  • callback: This parameter holds the function to be called for each element of the array. This function takes the mentioned parameters as below:
    • element: This parameter holds the current element of the array.
    • Index(Optional): This parameter holds the index of the current element within the array.
    • array(Optional): This parameter holds the reference to the original array.
  • thisParameter(Optional): This parameter holds the context to be passed as 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:

Examples
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!


Related Posts



Comments

Recent Posts
Tags