定义
reduce() 方法对数组中的每个元素执行一个由您提供的reducer函数(升序执行),将其结果汇总为单个返回值。
描述
有 initialValue 的情况
无 initialValue 的情况
reduce应用
1. 计算数组中每个元素出现的次数
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 }
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'
}
];
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. 计算购物车的总价
filter
遍历数组所有元素,返回符合要求的元素组成的数组
reduce
定义初始值为0,将此数组中元素(item为下标为0的数组元素)(item.price * item.count)与累计器(preValue,初始值为0)累加