reduce常用基础用法
数组里所有值的和
let arr = [0,1,2,3,4];
let sum = arr.reduce((acc,cur)=>{
return acc+cur;
})
console.log(sum); //10
累加对象数组里的值
注意:要累加对象数组中包含的值,必须提供初始值
let arr = [{x: 1}, {x:2}, {x:3}];
let sum = arr.reduce((acc,cur)=>{
return acc+cur.x;
},0)
console.log(sum); //6
将二维数组转化为一维
let arr = [[0, 1], [2, 3], [4, 5]];
let sum = arr.reduce((acc,cur)=>{
return acc.concat(cur);
},[])
console.log(sum); //[0, 1, 2, 3, 4, 5]
数组去重
var arr = [1,2,1,2,3,5,4,5,3,4,4,4,4];
var result = arr.sort((a,b)=>{return a-b}).reduce((initArr,cur)=>{
if(initArr.length===0||initArr[initArr.length-1]!==cur){
initArr.push(cur)
}
return initArr;
},[])
console.log(result); //[1, 2, 3, 4, 5]
计算数组中每个元素出现的次数
let arr = ['蔡徐坤','吴亦凡','篮球','RAP','大碗宽面','蔡徐坤','吴亦凡'];
let Namecount = arr.reduce((allNames,name)=>{
(name in allNames)? allNames[name]++:allNames[name] = 1;
return allNames;
},{});
console.log(Namecount) //{蔡徐坤: 2, 吴亦凡: 2, 篮球: 1, RAP: 1, 大碗宽面: 1}