Jamgreen Jamgreen - 2 months ago 23
Javascript Question

Group array of objects depending on values

I have an array of objects

[
{ values: [2, 7, 1] },
{ values: [1, 2, 7] },
{ values: [7, 1, 2] },
{ values: [3, 4, 5] },
{ values: [2, 1, 8] },
{ values: [2, 1, 8] },
]


I want to group these objects together with the other object with same values. So this array of objects should be grouped into 3 groups since the first 3 objects have the same values, the next object is alone and the last 2 objects have the same values.

As seen in the example, the values can have different orders, but should still be considered the same.

I am thinking about for each element to loop through the remaining elements and see if they are alike, but it will result in
O(n^2)
.

I guess I should remove elements from the array that has already been grouped.

So how could I, efficiently, group it as

[[first, second, third],[fourth],[fifth,sixth]]

ruX ruX
Answer

Something like this?

var data = [
  { values: [2, 7, 1] },
  { values: [1, 2, 7] },
  { values: [7, 1, 2] },
  { values: [3, 4, 5] },
  { values: [2, 1, 8] },
  { values: [2, 1, 8] },
];

var map = {};
for(obj of data) {
  console.log(obj)
  var key = obj.values.sort().join("-");
  if (!map[key]) map[key] = [];
  map[key].push(obj);
}

console.log(map)