Home > Web Front-end > JS Tutorial > body text

How to use flatMap function

不言
Release: 2019-02-21 13:50:00
Original
5052 people have browsed it

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))
{
    //返回的新数组元素
}
Copy after login

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>
Copy after login

The output result is:

[[3],[6],[9],[12],[15]] 
[3,6,9,12,15] 
[[3],[6],[9],[12],[ 15]
Copy after login

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>
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template