I need to group together all the pId together which has same cId entries. I have the following data -
const data = [{pId:"a", cId: [1,2]}, {pId:"b", cId: [1,2]}, {pId:"c", cId: [3]}];
const data1 = [{pId:"a", cId: [1,2,3]}, {pId:"b", cId: [1,2]}, {pId:"c", cId: [3]}];
const data2 = [{pId:"a", cId: [1,2,3]}, {pId:"b", cId: [1,2,3]}, {pId:"c", cId: [3]}];
Expected output -
data = [{pId:["a","b"], cId: [1,2]}, {pId:["c"],cId: [3]}]
data1 = [{pId:["a","b"], cId: [1,2]}, {pId:["a","c"],cId: [3]}]
data2 = [{pId:["a","b"], cId: [1,2,3]},{pId:["a","b","c"],cId: [3]}]
Please help, in the approach. Kindoff stuck, not able to think which qualifies all the cases
From what I can gather you’re looking to group based on array similarity in cId. I think you’re looking at something like this:
function unique (array) {
return Array.from(new Set(array));
}
function match (cIds) {
return function (x) {
return x.cId.join() == cIds;
}
}
function regroup () {
return unique(data.map(x => x.cId.join())
.map(cIds => ({
pId: data.filter(match(cIds)).map(x => x.pId),
cId: data.find(match(cIds)).cId
}));
}
data = regroup(data);
data1 = regroup(data1);
data2 = regroup(data2);
Please note that this is a very naive way of comparing arrays by values (there’s a lot of joins involved). This is not production-code ready, but you get the drift of how to handle this problem.