Skip to content Skip to sidebar Skip to footer

Group Items In Multidimensional Array By Same Value At Index

I have a multi-dimensional array like this: var arr = [ [x,x,1] , [x,x,2] , [x,x,2] , [x,x,3] , [x,x,3] , [x,x,3] ]; and I want to make it like this (grouping each sub-array accor

Solution 1:

Array#forEach solution.

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));

Solution 2:

You can first group arrays by using one object and then use map() and Object.keys() to return array as result.

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))

Solution 3:

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

Solution 4:

You could use a Map and generate the new array with Array#reduce in a single loop.

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)
        )(newMap), []);

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

Post a Comment for "Group Items In Multidimensional Array By Same Value At Index"