-1

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]
}
4
  • On what basis do you want to categorize them? Can you explain a bit? Commented Aug 5, 2022 at 15:39
  • 1
    Post some JavaScript, we are not a free code service, we fix your broken code. Commented Aug 5, 2022 at 15:42
  • @NullPointerException They're coordinates for triangles, and the output needs to be an array of the points in triangles which share at least one vertex; in the example - the first output array is all the points which appear in another triangle. Another output which would work would be an array of arrays of the triangles who all share a point, so rather than [[2,3,6,9,10],...] it would be [[2,3,9],[3,6,9],[3,6,10],[6,9,10]...] Commented Aug 5, 2022 at 15:48
  • @zer00ne , if I had code to be fixed I would post it! I've spent 3 days trying various nested for loops and recursive functions with no luck at all, I appreciate it's not a free code service but I've really run out of ideas and only need a hand with one function - Even just some logic I could try and implement myself would be helpful! Commented Aug 5, 2022 at 15:49

1 Answer 1

0

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.