数组中强大的reduce
# 数组中强大的reduce
# 定义
对数组中的每个元素执行一个由您提供的reducer函数(升序执行),将其结果汇总为单个返回值。
array.reduce(function(accumulator, arrayElement, currentIndex, arr), initialValue)
参数:
function(必须):数组中每个元素需要调用的函数
- total(必须),初始值, 或者上一次调用回调返回的值
- currentValue(必须),数组当前元素的值
- index(可选), 当前元素的索引值
- arr(可选),数组对象本身
initialValue(可选): 指定第一次回调 的第一个参数。
# 求和
let arr = [1,2,3,4];
arr.reduce((pre,cur) => pre + cur ); // 10
1
2
2
# 数组转化为对象
在实际业务开发中,你可能遇到过这样的情况,后台接口返回的数组类型,你需要将它转化为一个根据id
值作为key
,将数组每项作为value
的对象进行查找。
const userList = [
{
id: 1,
username: 'john',
sex: 1,
email: 'john@163.com'
},
{
id: 2,
username: 'jerry',
sex: 1,
email: 'jerry@163.com'
},
{
id: 3,
username: 'nancy',
sex: 0,
email: ''
}
];
const userObj = userList.reduce(function(acc, person){
return {...acc, [person.id]: person}
}, {});
console.log(userObj);
// {
// 1: {
// id: 1,
// username: 'john',
// sex: 1,
// email: 'john@163.com'
// },
// 2: {
// id: 2,
// username: 'jerry',
// sex: 1,
// email: 'jerry@163.com'
// },
// 3: {
// id: 3,
// username: 'nancy',
// sex: 0,
// email: ''
// }
// }
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
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
# 计算数组中每个元素出现的次数
var names = ['Alice', 'Bob', 'Tiff', 'Bruce', 'Alice'];
var countedNames = names.reduce(function (allNames, name) {
if (name in allNames) {
allNames[name]++;
} else {
allNames[name] = 1;
}
return allNames;
}, {});
// { 'Alice': 2, 'Bob': 1, 'Tiff': 1, 'Bruce': 1 }
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10