// 初始值为0
let array = [1, 3, 5];
console.log(
array.reduce((preValue, curValue, curIndex) => {
console.log(curIndex + "--" + preValue + "--" + curValue);
return preValue + curValue;
}, 0)
);
// 初始值为10
console.log("1111111111111111111111111111111111111111111");
let array1 = [1, 3, 5];
console.log(
array1.reduce((preValue, curValue, curIndex) => {
console.log(curIndex + "--" + preValue + "--" + curValue);
return preValue + curValue;
}, 10)
);
// 没有初始值
console.log("22222222222222222222222222222222222222222222");
let array2 = [1, 3, 5];
console.log(
array2.reduce((preValue, curValue, curIndex) => {
console.log(curIndex + "--" + preValue + "--" + curValue);
return preValue + curValue;
})
);
// 二维数组变一维
console.log("333333333333333333333333333333333333333333333");
let array3 = [
[0, 1],
[2, 3],
[4, 5],
];
console.log(
array3.reduce((acc, cur) => {
console.log("acc=", acc);
console.log("cur=", cur);
console.log("---------");
return acc.concat(cur);
}, [])
);
// 统计数组中元素次数
console.log("44444444444444444444444444444444444444");
const names = ["Alice", "Bob", "Tiff", "Bruce", "Alice"];
let countedNames = names.reduce(function (allNames, name) {
if (name in allNames) {
allNames[name]++;
} else {
allNames[name] = 1;
}
return allNames;
}, {});
console.log(countedNames);
//按属性对object分类
console.log("55555555555555555555555555555555555555555555");
var people = [
{ name: "Alice", age: 21 },
{ name: "Max", age: 20 },
{ name: "Jane", age: 20 },
];
function groupBy(objectArray, property) {
return objectArray.reduce(function (acc, obj, index) {
var key = obj[property]; //=> key=21,20,20
if (!acc[key]) {
acc[key] = []; //分别对key为21和20的时候,初始化两个空数组,用来存放对象
}
acc[key].push(obj); //将符合key=21或20的对象压栈
return acc;
}, {});
}
var groupedPeople = groupBy(people, "age");
console.log(groupedPeople);