鍍金池/ 問(wèn)答/HTML/ js根據(jù)條件將一個(gè)一維對(duì)象數(shù)組轉(zhuǎn)為二維數(shù)組

js根據(jù)條件將一個(gè)一維對(duì)象數(shù)組轉(zhuǎn)為二維數(shù)組

請(qǐng)問(wèn)下,如何把下面的數(shù)組arrayFirst,根據(jù)相同的index轉(zhuǎn)成arrayTwo

var arrayFirst = [{
    index: 1,
    datas: han
},
{
    index: 1,
    datas: hu
}, {
    index: 2,
    datas: zhang
},
{
    index: 2,
    datas: wang
}

]

var arrayTwo = [[{
    index: 1,
    datas: han
},
{
    index: 1,
    datas: hu
}], [{
    index: 2,
    datas: zhang
},
{
    index: 2,
    datas: wang
}]]

看著很簡(jiǎn)單,但是確不知道怎么做才好

回答
編輯回答
故林

es6實(shí)現(xiàn)起來(lái)很簡(jiǎn)潔,es5就參見(jiàn)樓上吧

var arrayFirst = [
  {
    index: 1,
    datas: 'han'
  },
  {
    index: 1,
    datas: 'hu'
  }, {
    index: 2,
    datas: 'zhang'
  },
  {
    index: 2,
    datas: 'wang'
  }
];

var arrayTwo = Object.values(arrayFirst.reduce((res, item) => {
  res[item.index] ? res[item.index].push(item) : res[item.index] = [item];
  return res;
}, {}));

console.log(arrayTwo)
2017年5月18日 10:38
編輯回答
我不懂

map方法 比較好理解:

            var map = new Map();
            var newArr = [];
            arrayFirst.forEach(function(item,i){
                map.has(item.index) ? map.get(item.index).push(item) : map.set(item.index,[item])
            })
            newArr = [...map.values()];
            
            console.log(newArr)
2018年8月29日 06:02
編輯回答
夢(mèng)一場(chǎng)

不一一回復(fù)了,大家的辦法都特別好,把需求處理完,再挨個(gè)試大家的方案,再次謝謝所有回答和參與本問(wèn)題的朋友!

2017年8月23日 11:07
編輯回答
喵小咪

先歸類(lèi),再轉(zhuǎn)數(shù)組

function convert (arr) {
    var map1 = {};
    while(arr.length) {
        let current = arr.pop(); // 會(huì)影響原數(shù)組
        map1[current.index] = map1[current.index] || [];
        map1[current.index].push(current);
    }
    
    return Object.keys(map1).map(key => map1[key]);
}
2018年3月25日 16:04
編輯回答
影魅

先按 index 把數(shù)組排個(gè)序,然后在利用 slice/splice 切數(shù)組, 切出來(lái)的組成新的二維數(shù)組

利用對(duì)象把 index 的值作為屬性, 把對(duì)應(yīng)的數(shù)組元素作為屬性值數(shù)組的元素, 最后把對(duì)象的屬性值組成新的二維數(shù)組

2017年12月16日 06:08
編輯回答
護(hù)她命
// 創(chuàng)建映射
var map = arrayFirst.reduce((p, c) => [p[c.index] = p[c.index] || [],
                                       p[c.index].push(c), p][2], {})
// 獲取映射分類(lèi)下的數(shù)組                                       
var result = Object.keys(map).map(i => map[i])
2017年2月5日 14:26
編輯回答
下墜
var arrayTwo = [];
var indexGroup = arrayFirst.map(v => v.index);
var flag = [];
for(var i = 0; i<indexGroup.length; i++) {
    var index = indexGroup[i];
    if(flag[index]) continue;
    flag[index] = 1;
    var groupArray = arrayFirst.filter(v => v.index === index);
    arrayTwo.push(groupArray);
}
2017年3月6日 12:48