Ignite

神奇的reduce

2019-08-25

reduce ( ) 这个函数有些复杂,不知到怎么描述好,直接看例子吧:

  • func:接受4个参数得函数,
    previous, current, index, array,之前值,当前值,索引,数组本身。func的返回值,会作为下一次迭代时previous的值。
  • initialValue:可选,表示初始值,如果指定initialValue,则作为初始时previous的值,如果缺省,数组得第一个元素为previous值,第二个元素为current。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
var arr = [1, 2, 3, 4, 5];
var sum = arr.reduce(function(previous, current, index, array){
return previous + current;
});
console.log(sum); // 15

过程展开如下:
// 初始:
previous = initialValue = 1, current = 2;
// 第一次迭代 之后
previous = 1 + 2 = 3, current = 3;//current 向后移动一个元素
// 第二次迭代之后
previous = 3 + 3 = 6, current = 4;
// 第三次迭代之后
previous = 6 + 4 = 10, current = 5;
// 第四次迭代之后
previous = 10 + 5 = 15 ,current = undefined// 没有了,退出,返回15;

拓展:reduceRight()

和reduce类似,只不过从数组结尾开始,从右向左迭代。

应用:

  • json数组去重
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
let arr = [{
"name": "ZYTX",
"age": "Y13xG_4wQnOWK1Qw",
"gender": "AAAAAA.doc"
}, {
"name": "ZYTA",
"age": "Y13xG_4wQnOWK1Qw",
"gender": "BBBBBB.doc"
}, {
"name": "ZDTX",
"age": "Y13xG_4wQnOWK1Qw",
"gender": "CCCCCC.doc"
}, {
"name": "ZYTX",
"age": "Y13xG_4wQnOWK1Qw",
"gender": "AAAAAA.doc"
}];
let hash = {};
arr = arr.reduce(function(item, next) {
hash[next.name] ? '' : hash[next.name] = true && item.push(next);
return item
}, [])
console.log(arr);
  • 数组去重
1
2
3
4
5
6
7
8
let arr = [1,2,1,2,3,5,4,5,3,4,4,4,4];
let result = arr.sort().reduce((init, current) => {
if(init.length === 0 || init[init.length-1] !== current) {
init.push(current);
}
return init;
}, []);
console.log(result); //[1,2,3,4,5]
  • reduce 实现 promise 串行执行
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
function runPromiseInSequence(arr, input) {
return arr.reduce(
(promiseChain, currentFunction) => promiseChain.then(currentFunction),
Promise.resolve(input)
);
}

// promise function 1
function p1(a) {
return new Promise((resolve, reject) => {
resolve(a * 5);
});
}

// promise function 2
function p2(a) {
return new Promise((resolve, reject) => {
resolve(a * 2);
});
}

// function 3 - will be wrapped in a resolved promise by .then()
function f3(a) {
return a * 3;
}

// promise function 4
function p4(a) {
return new Promise((resolve, reject) => {
resolve(a * 4);
});
}

const promiseArr = [p1, p2, f3, p4];
runPromiseInSequence(promiseArr, 10)
.then(console.log);

拓展:更加简便的方法,使用异步函数来实现
runPromiseInSequence可以简化为:Ï

1
2
3
4
5
async function runPromiseInSequence(myPromises) {
for (let value of myPromises) {
await value();
}
}
使用支付宝打赏
使用微信打赏

若你觉得我的文章对你有帮助,欢迎点击上方按钮对我打赏

扫描二维码,分享此文章