js中reduce的奇淫技巧

很多人一看到 reduce,就想到了可以用它来求和,

其实,reduce还有其他很好用的功能, 比如统计元素个数,获取最大/小值,扁平化数组

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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
// reduce(function(total, cur, index, arr){}, init_value);

// 计算总数
let arr = [12, 13, 14];
let total = arr.reduce((total, cur, index, array) => {
console.log(total, cur, index, array);
return total + cur;
}, 1000);
console.log('共计', total); // 1039
console.log('===============');
/**
* 1000 12 0 [ 12, 13, 14 ]
1012 13 1 [ 12, 13, 14 ]
1025 14 2 [ 12, 13, 14 ]
共计 1039
*/

let arr_obj = [{
name: 'dottie',
score: 20
}, {
name: 'daejong',
score: 22
}];
let totalScore = arr_obj.reduce((total, cur) => total + cur.score, -10);
console.log("总分", totalScore); // 32
console.log('===============');


// 数组最大值
let maxValue = arr.reduce((pre, cur) => cur > pre ? cur : pre);
console.log('最大值', maxValue);
console.log('==============='); // 14

// 数组对象最大值
let maxScoreObj = arr_obj.reduce((pre, cur) => cur.score > pre.score ? cur : pre);
console.log('最大分数的对象', maxScoreObj); // { name: 'daejong', score: 22 }
console.log('===============');


// 自定义拼接方式
const objArr = [{name: 'daejong'}, {name: 'miss'}, {name: 'dottie'}];
const res = objArr.reduce((pre, cur, index, arr) => {
if (index === 0) {
return cur.name;
}
else if (index === (arr.length - 1)) {
return pre + ' >>> ' + cur.name + "!";
}
else {
return pre + ' does ' + cur.name;
}
}, ''); // 这里的初始值决定后来的total的数据结构。这是返回值就是字符串。
console.log('', res); // daejong does miss >>> dottie!
console.log('===============');


// 求元素出现的次数 **** 好用的。
let arr1 = [1, 2, 1, 3, 4, 3, 4, 2, 3 ,2 ,5];
let arr1Res = arr1.reduce((total, cur) => {
total[cur] ? total[cur]++ : total[cur] = 1;
return total;
}, {}); // 注意这里的初始值, 很重要。决定后来的total的数据结构, 这里返回值就是数组。
console.log('统计次数', arr1Res); // { '1': 2, '2': 3, '3': 3, '4': 2, '5': 1 }
console.log('===============');


// 扁平化数组。
let arr2 = [[1, 2, 8], [3, 4, 9], [5, 6, 10]];
let res2 = arr2.reduce((x, y) => x.concat(y), []);
console.log('扁平化后数组', res2); // [ 1, 2, 8, 3, 4, 9, 5, 6, 10 ]
console.log('===============');