编辑代码

//数组求和
var sum=[1,2,3,4].reduce((acc,cur)=>acc+cur,0)
console.log(sum)
//累加对象数组里的值
var sum2 = [{x:1},{x:2},{x:3}].reduce(function(acc,cur){
    return acc+cur.x
},0)

console.log(sum2)

//二维数组转为一维
var sum3 = [[1,2],[3,4],[5,6]].reduce((acc,cur)=>acc.concat(cur),[])
console.log(sum3)

//计算数组中每个元素出现的次数
var names = ['Alice', 'Bob', 'Tiff', 'Bruce', 'Alice']; 
var countedNames = names.reduce((allNames,name)=>{
    if(name in allNames){
        allNames[name]++
    }else{
        allNames[name]=1
    }
    return allNames
},{})
console.log(countedNames)

//按属性对object进行分类
var people = [
  { name: 'Alice', age: 21 },
  { name: 'Max', age: 20 },
  { name: 'Jane', age: 20 }
];
function groupBy(objArray,property){
    return objArray.reduce((acc,obj)=>{
        var key = obj[property]
        if(!acc[key]){
            acc[key]=[]
        }
        acc[key].push(obj)
        return acc
    },{})
}
var res = groupBy(people,'age')
console.log(res)

var friends = [{
  name: 'Anna',
  books: ['Bible', 'Harry Potter'],
  age: 21
}, {
  name: 'Bob',
  books: ['War and peace', 'Romeo and Juliet'],
  age: 26
}, {
  name: 'Alice',
  books: ['The Lord of the Rings', 'The Shining'],
  age: 18
}];

var all = friends.reduce(function(prev, curr) {
  return [...prev, ...curr.books];
},[]);

console.log(all)