Home > database >  How do I group repeated integers from a 2d array in javascript
How do I group repeated integers from a 2d array in javascript

Time:08-06

I have an array of 3 value arrays, and I need to convert them into a set of arrays where each array is made up of the values which were common between arrays, so my input of

[[2,3,9], [1,4,7], [3,6,9], [1,7,5], [7,5,8], [9,6,10], [3,6,10], [1,8,5]]

becomes

[[2,3,6,9,10],[1,4,5,7,8]]

Order is not important. I've found similar questions such as Group same values in an array within an array in JS but it seems slightly different to my case, but I imagine using reduce is the way to go, but I don't entirely understand how. I have tried creating an object using the following format, but couldn't get from there to an answer:

{
    vertex: 3,
    triangles: [2,3,9], [3,6,9], [3,6,10]
}

CodePudding user response:

Here is one algorithm. Take first item from array and check first item array has any common array. If they have common item, then merge it and move the merged array to first item of array. If no common item, then add to result array.

const merge = (arr) => {
  const result = [];
  while (arr.length > 0) {
    let first = arr.shift();
    const idx = arr.findIndex((items) =>
      items.some((item) => first.includes(item))
    );
    if (idx !== -1) {
      first = first.concat(arr[idx]);
      arr.splice(idx, 1);
      arr.unshift(first);
    } else {
      result.push(first);
    }
  }
  return result.map(items => [...new Set(items)]);
};

const data = [
  [2, 3, 9],
  [1, 4, 7],
  [3, 6, 9],
  [1, 7, 5],
  [7, 5, 8],
  [9, 6, 10],
  [3, 6, 10],
  [1, 8, 5],
];

console.log(merge(data));

  • Related