按属性对object分类
let peple=[{name:'Alice',age:21},{name: 'Mex', age: 20},{name:'Jane',age:20}
}function groupBy (objectArray, property) {return objectArray.reduce(function(pre, cur){let key=cur[property]if(!pre[key]){pre[key]=[]}pre[key].push(cur)return pre},{})
}
let groupByPeople-groupBy(peple, 'age')console. log(groupByPeople)
/**{
'20': [ { name: 'Mex', age: 20 }, { name: 'Jane', age: 20 } ],
'21': [ { name: 'Alice', age: 21 } ]
}*/
使用扩展运算符和initialValue绑定包含在对象数组中的数组
let 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
}]let allbook=friends.reduce((pre,cur) ->{let key=cur['books']return [ ... pre, ... key]},['alphoter'])
console.log(allbook);/**
[
'alphoter',
'Bible',
'Harry Potter',
'War and peace',
'Romeo and Juliet',
'The Lord of the Rings',
'The Shining
]
*/
ヾ( ̄▽ ̄)Bye~Bye~