0

题目描述

从后端获取的接口数值是动态的,id和name的数值都是动态。json的格式如下,举个简单的例子:

var arr = [
    {id:1,name:2},
    {id:2,name:13},
    {id:3,name:2},
    {id:10,name:2}
];

现在,我需要根据name相同获取到的最终效果如下:

arr1 = [{id:2,name:13}]
arr2 = [
    {id:1,name:2},
    {id:3,name:2},
    {id:10,name:2}
]

也就是说 需要拆分出来一个name不相同的数组;一个name值相同的数组;
求各位老大帮忙解答一下?

Mteer 1
2018-12-24 提问
1 个回答
0
var arr = [
    {id:1,name:2},
    {id:2,name:13},
    {id:3,name:2},
    {id:10,name:2}
];
function f(arr) {
    var mp= {}
    var ret = []
    arr.forEach(item => {
        if (typeof mp[item.name] === 'number') {
            ret[mp[item.name]].push(item)
        } else {
            mp[item.name] = ret.length
            ret.push([item])
        }
    })
    return ret
}
console.log(f(arr))

撰写答案

推广链接