请问如何把一个带有相同元素值的数组归类组成一个新的二维数组?

请问如何把一个带有相同元素值的数组归类组成一个新的二维数组?

相关代码

    let arr = [{
            code: "China",
            name: "xiaohuai"
        },
        {
            code: "Africa",
            name: "neiLuoBi"
        },
        {
            code: "Asia",
            name: "hanGuo"
        },
        {
            code: "China",
            name: "tnnyang"
        },
        {
            code: "Africa",
            name: "nanFei"
        },
        {
            code: "China",
            name: "yangMan"
        }
    ]

归类为下面这种形式

    let arr2 = [{
        China: [{
                name: "xiaohuai"
            },
            {
                name: "tnnyang"
            },
            {
                name: "yangMan"
            }
        ],
        Africa: [{
                name: "neiLuoBi"
            },
            {
                name: "nanFei"
            }
        ],
        Asia: [{
            name: "hanGuo"
        }]
    }]
阅读 2.6k
1 个回答
let result = arr.reduce((result, item) => {
    let data = {name: item.name}
    result[item.code] ? result[item.code].push(data) : (result[item.code] = [data]);
    return result
}, Object.create(null));

result = [result]
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏