在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/HTML/ js根據條件將一個一維對象數組轉為二維數組

js根據條件將一個一維對象數組轉為二維數組

請問下,如何把下面的數組arrayFirst,根據相同的index轉成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
}]]

看著很簡單,但是確不知道怎么做才好

回答
編輯回答
故林

es6實現起來很簡潔,es5就參見樓上吧

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
編輯回答
夢一場

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

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

先歸類,再轉數組

function convert (arr) {
    var map1 = {};
    while(arr.length) {
        let current = arr.pop(); // 會影響原數組
        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 把數組排個序,然后在利用 slice/splice 切數組, 切出來的組成新的二維數組

利用對象把 index 的值作為屬性, 把對應的數組元素作為屬性值數組的元素, 最后把對象的屬性值組成新的二維數組

2017年12月16日 06:08
編輯回答
護她命
// 創(chuàng)建映射
var map = arrayFirst.reduce((p, c) => [p[c.index] = p[c.index] || [],
                                       p[c.index].push(c), p][2], {})
// 獲取映射分類下的數組                                       
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