将多维数组中的项目按索引处的相同值分组

时间:2017-04-01 14:26:05

标签: javascript

我有一个像这样的多维数组:

var arr = [ [x,x,1] , [x,x,2] , [x,x,2] , [x,x,3] , [x,x,3] , [x,x,3] ];

我想这样做(根据匹配的arr[i][2]值对每个子数组进行分组):

var arr = [ [[x,x,1]] , [[x,x,2],[x,x,2]] , [[x,x,3],[x,x,3],[x,x,3]] ];

我的尝试越来越啰嗦,我很惭愧将它们发布在这里。任何有效的建议都非常感谢!

4 个答案:

答案 0 :(得分:1)

您可以先使用一个对象对数组进行分组,然后使用map()Object.keys()返回数组作为结果。

var arr = [["x","x", 1],["x","x", 2],["x","x", 2],["x","x", 3],["x","x", 3],["x","x", 3]];

var obj = {}
arr.forEach(function(e) {
  if(!obj[e[2]]) obj[e[2]] = []
  obj[e[2]].push(e)
});

var result = Object.keys(obj).map(e => obj[e]);
console.log(JSON.stringify(result))

答案 1 :(得分:1)

var x = 'x';
var arr= [ [x,x,1] , [x,x,2] , [x,x,2] , [x,x,3] , [x,x,3] , [x,x,3] ];

var working = arr.reduce(function(acc, current) {
  (acc[current[2]] || (acc[current[2]] = [])).push(current);
  return acc;
}, {});

var result = Object.keys(working).map(function(k) { return working[k] });

console.log(JSON.stringify(result)); // stringified just to avoid scrolling

答案 2 :(得分:1)

Array#forEach解决方案。

var arr = [["x","x", 1],["x","x", 2],["x","x", 2],["x","x", 3],["x","x", 3],["x","x", 3]], obj = {};

arr.forEach(v => (obj[v[2]] || (obj[v[2]] = [])).push(v));
var res = Object.keys(obj).map(v => obj[v]);

console.log(JSON.stringify(res));

答案 3 :(得分:1)

您可以使用Map并在单个循环中使用Array#reduce生成新数组。

var array = [['x', 'x', 1], ['x', 'x', 2], ['x', 'x', 2], ['x', 'x', 3], ['x', 'x', 3], ['x', 'x', 3]],
    grouped = array.reduce((map =>
        (r, a) => 
            (!map.has(a[2]) && map.set(a[2], r[r.push([]) - 1]), map.get(a[2]).push(a), r)
        )(new Map), []);

console.log(grouped);
.as-console-wrapper { max-height: 100% !important; top: 0; }