var sum=[0,1,2,3].reduce(function(accumulator,currentValue){ return accumulator+currentValue; },0) //6 //累加对象数组里的值 var InitValue=0; var sum=[{x:1},{x:2},{x:3}].reduce(function(accumulator,currentValue){ return accumulator+currentValue; },InitValue); console.log(sum);//6
将二维数组转为一维
1
var flattened=[[0,1],[2,3],[4,5],[6,7]].reduce(function(a,b){return a.concat(b);},[])
计算数组中每个元素出现的个数
1 2 3 4 5 6 7 8 9 10 11
var names=['Alice','Bob','Ann','Alice','Bob']; var countNames=names.reduce((allNames,name)=>{ if(name in allNames){ allNames[name]++; } else{ allNames[name]=1; } return allNames; },{}); console.log(countNames);
按照属性对object分类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
var people=[ {name:'Alice',age:20}, {name:'Max',age:20}, {name:'Jane',age:21} ] functiongroupBy(objectArray,property){ return objectArray.reduce(function(acc,obj){ var key=obj[property]; if(!acc[key]){ acc[key]=[]; } acc[key].push(obj); return acc;
},{}); } var groupedPeople=groupBy(people,'age'); console.log(groupedPeople);
使用扩展运算符绑定包含在对象数组中的数组
1 2 3 4 5 6 7 8 9
var friends=[{ name:'Anna', books:['Bible','Harry Potter'], age:21 }, {name:'Bob',books:['War and Peace'],age:16}, {name:'Mike',books:['The Shining','The Lord of the Rings'],age:18}]; var allBooks=friends.reduce((prev,curr)=>{return [...prev,...curr.books]},['Alphabet']); console.log(allBooks);
数组去重
1 2 3 4 5 6 7 8 9
let myArray=[6,6,6,2,3,3,4,4,4,5]; let myOrderedArray=myArray.reduce((accumulator,currval)=>{ if(accumulator.indexOf(currval)==-1){ accumulator.push(currval); } return accumulator;