Reputation: 2308
Following is an array of product which has been find and process on contact data and creates the possible array of merge occurrences. In the following arrProduct, I would like to filter duplicate array and merge with existing array and finally create a unique array product called arrFinalProduct.
Array product
arrProduct =
[
[ 0 ],
[ 1, 2 ],
[ 2 ],
[ 3 ],
[ 4, 5, 6, 10 ],
[ 5, 6, 7, 11 ],
[ 6 ],
[ 7, 11 ],
[ 8 ],
[ 9 ],
[ 10 ],
[ 11 ],
[ 12 ],
[ 13, 14 ],
[ 14 ]
]
Final product
arrFinalProduct =
[
[ 0 ],
[ 1, 2 ],
[ 3 ],
[ 4, 5, 6, 7, 10, 11 ],
[ 8 ],
[ 9 ],
[ 12 ],
[ 13, 14 ]
]
arrProduct is the product array and arrFinalProduct is the final product array. The basic logic is that we require merging array, if any occurrences match found from an array.
Let's say value 0 is not found in any index in arrProduct so it does not merge and push into arrFinalProduct, arrProduct value 2 is found on 1st and 2nd index so it may merge with 1st index and become [1,2] and delete 3rd index of [2]. arrProduct index 5 have two common value 5 and 6 and it also in index 6 so it may merge into 1 and become "4,5,6,7" and so on...
This process is going to process data recursively until I found unique value from an array. So it probably merges array horizontally.
Hope reader may get an enough idea.
Upvotes: 1
Views: 96
Reputation: 386512
Basically you could search for exisitent items in the result set and join the arrays with same items.
The order of items is the same as the appearance.
var array = [[0], [1, 2], [2], [3], [4, 5, 6, 10], [5, 6, 7, 11], [6], [7, 11], [8], [9], [10], [11], [12], [13, 14], [14]],
result = array.reduce(function (r, a) {
r.some(function (b, i, bb) {
if (a.some(c => b.includes(c))) {
bb[i] = [...new Set(b.concat(a))];
return true;
}
}) || r.push(a);
return r;
}, []);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Upvotes: 1