Concept: A function that takes another function as a parameter is called a higher-order function. For example, map, reduce and other methods of traversing a number array usually have a function parameter.
Array.map
The map method of the array iterates over the array and returns an array of the return values of the callback function, as shown in the following example:
let arr = [1.2.3.4]
let res = arr.map((val,idx) = >{
return val+1
})
console.log(res);/ / 5-tetrafluorobenzoic [2]
Copy the code
The callback function accepts three values: val, IDx, arr(that is, array element, subscript, and primitive array)
Array.reduce
The reduce method of the array returns a final value processed by the function after iterating through the array. See the code
let arr = [1.2.3.4]
let res = arr.reduce((total,now) = >{
return total + now
},0)
console.log(res);/ / 10
Copy the code
In fact, reduce is a cumulative process. It sends the result of each round of processing to the callback function of the next round as a parameter (the total parameter), and the total value of the first round can be specified, that is, the second parameter of reduce function. I write 0 here. If not specified, the first element in the array is used as the total value. The value of now is the current element being iterated over, and the return value of the last processing is returned
Array.flatMap
FlatMap is actually a map function that expands an array of layers. Flat means flattening, and flatMap means flattening the returned value of a layer. Let’s see the differences between map and flatMap
let arr = [1.2.3.4]
let res1 = arr.map((val) = >[val+1])
let res2 = arr.flatMap((val) = >[val+1])
let res3 = arr.flatMap((val) = >[[val+1]])
console.log(res1);/ / [[2], [3], [4], [5]]
console.log(res2);/ / 5-tetrafluorobenzoic [2]
console.log(res3);/ / [[2], [3], [4], [5]]
Copy the code
You can see that flatMap turns the returned two-dimensional array into a one-dimensional array and a three-dimensional array into a two-dimensional array