Skip to content

利用reduce实现数组分组

typescript
let arr = [{
    type: 1,
    name: '手机'
},
{
    type: 2,
    name: '空调'
},
{
    type: 3,
    name: '盆栽'
},
{
    type: 1,
    name: '翻盖手机'
},
{
    type: 3,
    name: '植物'
}]

function arrGroup() {
    // acc合计值,obj当前遍历item
    let outcome = arr.reduce((acc, obj) => {
        const { type, name } = obj;
        // 初始 acc[type] 肯定不存在,给一个默认空数组
        // 再次遍历 acc[type] = acc[type] 不会做修改
        acc[type] = acc[type] || []; 
        // 给数组push数据
        acc[type].push(name);
        return acc; // 返回最新的acc
    }, {}); // acc初始值为空对象 {} 
    console.log('结果', outcome)
}
arrGroup();

基于 MIT 许可发布