前端理论总结(js)——reduce相关应用方法

文章介绍了如何使用JavaScript的reduce方法对对象数组按指定属性进行分组,并展示了如何使用扩展运算符合并多个数组。示例中对人员按年龄和朋友的书籍列表进行了操作。
摘要由CSDN通过智能技术生成

按属性对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~

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值