Saturday, November 16, 2024
Google search engine
HomeLanguagesJavascriptJavaScript Array flatMap() Method

JavaScript Array flatMap() Method

The Javascript array flatMap() is an inbuilt method in JavaScript that is used to flatten the input array element into a new array. This method first of all maps every element with the help of a mapping function, then flattens the input array element into a new array.

Syntax:

let A = array.flatMap(function callback(current_value, index, Array)) {
// It returns the new array's elements.
}

Parameters:

  • current_value: It is the input array element.
  • index:
    • It is optional.
    • It is the index of the input element.
  • Array: 
    • It is optional.
    • It is used when an array map is called.

Return Values: It returns a new array whose elements are the return value of the callback function.

Example 1: in this example, we will see the basic use of the array.flatMap() method for flattening an array. 

javascript




// Taking input as an array A having some elements.
let A = [1, 2, 3, 4, 5];
 
// Mapping with map method.
b = A.map(x => [x * 3]);
console.log(b);
 
// Mapping and flatting with flatMap() method.
c = A.flatMap(x => [x * 3]);
console.log(c);
 
// Mapping and flatting with flatMap() method.
d = A.flatMap(x => [[x * 3]]);
console.log(d);


Output

[ [ 3 ], [ 6 ], [ 9 ], [ 12 ], [ 15 ] ]
[ 3, 6, 9, 12, 15 ]
[ [ 3 ], [ 6 ], [ 9 ], [ 12 ], [ 15 ] ]

Example 2: This flatting can also be done with the help of reducing and concat.

javascript




// Taking input as an array A having some elements.
let A = [1, 2, 3, 4, 5];
console.log(A.flatMap(x => [x * 3]))
 
// is equivalent to
b = A.reduce((acc, x) => acc.concat([x * 3]), []);
console.log(b);


Output

[ 3, 6, 9, 12, 15 ]
[ 3, 6, 9, 12, 15 ]

We have a complete list of Javascript Array methods, to check those please go through this Javascript Array Complete reference article.

Supported Browser:

  • Google Chrome 69 and above
  • Edge 79 and above
  • Firefox 62 and above
  • Opera 56 and above
  • Safari 12 and above

Note: This method is available in Firefox Nighty only.

We have a Cheat Sheet on Javascript where we covered all the important topics of Javascript to check those please go through Javascript Cheat Sheet-A Basic guide to JavaScript.

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments