Home  >  Article  >  Web Front-end  >  How to use flatMap function

How to use flatMap function

不言
不言Original
2019-02-21 13:50:005039browse

array.flatmap() is a built-in function in javascript that flattens input array elements into a new array. This method first maps each element using a mapping function and then flattens the input array elements into a new array. Let's take a look at the specific usage of flatMap().

How to use flatMap function

The basic syntax of flatMap() is:

var A = array.flatMap(function callback(current_value, index, Array))
{
    //返回的新数组元素
}

callback: This is a new array with the help of three parameters A function that generates elements as follows:

current_value: It is the input array element.

index: This is optional. It is the index of the input element.

Array: This is optional. It is used when calling array mapping.

Let’s look at two specific examples

Example 1:

The code is as follows

<script>  
var A = [ 1, 2, 3, 4, 5 ];  
b = A.map(x => [x * 3]); 
document.write(b);  
c = arr1.flatMap(x => [x * 3]); 
document.write(c);  
d = arr1.flatMap(x => [[ x * 3 ]]); 
document.write(d); 
</script>

The output result is:

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

Example 2:

The code is as follows

<script> 
var A = [ 1, 2, 3, 4, 5 ]; 
array.flatMap(x => [x * 3]); 
b = A.reduce((acc, x) => acc.concat([ x * 3 ]), []); 
document.write(b); 
</script>

The output result is: [3,6,9,12,15]

This article has ended here. For more exciting content, you can pay attention to other related column tutorials on the PHP Chinese website! ! !

The above is the detailed content of How to use flatMap function. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn