## Map(), filter() and reduce() in Array

One, map()

map is used to traverse the value of each item in the array and perform a series of operations.

``````const prices = [19.99, 4.95, 25, 3.50];
let new_prices = [];
for(let i = 0; i < prices.length; i++) {
new_prices.push(prices[i] * 1.06);
}
``````

Writing with map is much easier:

``````const prices= [19.99, 4.95, 25, 3.50];
let new_prices = prices.map(price => price *1.06);``````

Two, filter()

The fiter is used to filter the eligible values ​​in the array.

``````const numbers = [1,2,3,4,5,6,7,8];
let odds = [];
for(let i = 0; i < numbers.length; i++) {
if(numbers[i] % 2 == 1) {
odds.push(numbers[i]);
}
}``````

Writing with filter is much easier:

``````constnumbers = [1,2,3,4,5,6,7,8];
let odds = numbers.filter(num => num % 2);``````

Three, reduce()

Reduce is an accumulator, used to accumulate the value of the entire array, can have an initial value.

``````const donations = [5, 20, 100, 80, 75];
let total = 10;
for(let i = 0; i < donations.length; i++) {
total += donations[i];
}``````

It is much easier to write with reduce:

``````const donations = [5, 20, 100, 80, 75];
let total = donations.reduce((total,donation)=> {
}, 10);``````

Reduce is also often used in function composition.

``````// demo flowRight  参考函数 g(f(x))  flowRight(g, f) ...args 为需要合并的函数 数组
function flowRight (...args){
// value 为执行 函数的初始值
return function (value) {
return args.reverse().reduce(function (acc, func) {
return func(acc)
}, value)
}
}
const compose = (...args) => value => args.reverse().reduce((acc, fnuc) => func(acc) , value)``````

### Guess you like

Origin blog.csdn.net/qq_40289624/article/details/109572283
Recommended
Ranking
Daily