AppDividend
Latest Code Tutorials

Javascript Array FlatMap Example | Array.prototype.flatMap() Tutorial

0

Javascript Array FlatMap Example | Array.prototype.flatMap() Tutorial is today’s topic. The flatMap() method first maps each element using the map function, then flattens the result into the new array.  It is identical to the Javascript Array map followed by the Javascript Array flat of depth 1, but flatMap() method is often quite useful, as merging both into one method is slightly more efficient.

Javascript Array FlatMap Example

The array.flatMap() is an inbuilt Javascript function which is used to flatten the input array element into the new array. Array flatMap() first of all map every element with the help of mapping function, then flattens the input array element into the new array.

The syntax for flatMap() function is following.

let new_array = arr.flatMap(function callback(currentValue[, index[, array]]) {
    // return element for new_array
}[, thisArg])

It returns a new array with each element being the result of the callback function and flattened to a depth of 1. It has a callback function as a parameter which has the following arguments.

The currentValue is the current element being processed in the array.

The index is an optional parameter, and it is the index of the current element being processed in the array.

An array is an optional argument, and it is the array on which map function is called.

Let’s see the following example.

// app.js

let arrA = [1, 2, 3, 4];
let arrB = arrA.flatMap(x => [x * 2]);
console.log(arrB);

The output is following.

 

Javascript Array FlatMap Example | Array.prototype.flatMap() Tutorial

Let’s see another example.

// app.js

let arrA = [1, 2, 3, 4];
let arrB = arrA.flatMap(x => [[x * 2]]);
console.log(arrB);

The output is following.

 

Javascript Array FlatMap Example

Finally, Javascript Array FlatMap Example Tutorial is over.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.