Quantcast
Channel: Active questions tagged javascript - Stack Overflow
Viewing all articles
Browse latest Browse all 142410

How in JS to group subarrays by common elements

$
0
0

I have an array of subarrays. Each subarray has at least one element which is duplicated at least in one more subarray. For example:

[
    ['aaa', 'bbb', 'ccc'],
    ['ddd', 'aaa'],
    ['aaa', 'bbb', 'ccc', 'eee'],
    ['kkk', 'mmm', 'nnn'],
    ['mmm', 'ooo']
]

In this case 'ddd' and 'eee' are not duplicated anywhere, but another elements in the same subarrays are duplicated at least in one more subarray. I need to group elements in new subarrays to receive the following output:

[
    ['aaa', 'bbb', 'ccc', 'ddd', 'eee'],
    ['kkk', 'mmm', 'nnn', 'ooo']
]

In other words, I need to group "friends". So if 'ddd' is a "friend" somewhere for 'aaa' and if 'eee' is a friend somewhere for 'bbb' and 'aaa' and 'bbb' also are friends, we group them all in one new subarray. But 'mmm' is not a friend for 'aaa', 'bbb' etc. but is a friend for kkk and nnn and ooo, so group them in another subarray


Viewing all articles
Browse latest Browse all 142410

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>