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().
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!