I was trying to merge the 2d array which has similar element in it.
let result = [
[
{ position: '00', symbol: 'AA' },
{ position: '01', symbol: 'AA' },
{ position: '02', symbol: 'AA' },
],
[
{ position: '30', symbol: 'BB' },
{ position: '31', symbol: 'AA' },
{ position: '32', symbol: 'AA' },
],
[
{ position: '00', symbol: 'AA' },
{ position: '10', symbol: 'AA' },
],
];
each of array might have different length
OUTPUT should be:
[
[
{ position: '00', symbol: 'AA' },
{ position: '01', symbol: 'AA' },
{ position: '02', symbol: 'AA' },
{ position: '10', symbol: 'AA' },
],
[
{ position: '30', symbol: 'BB' },
{ position: '31', symbol: 'AA' },
{ position: '32', symbol: 'AA' },
],
];
Explanation: position '00' exists two times so, that particular array merged with first one and after merge loop will again start from 0 to check other duplicates and merge until finish all.
UPDATE
Somehow I have managed to get expected output but Time complexity is really high. need to optimize. Please help if anyone have some optimized solution
This is my code which gave exact same result
for (let i = 0; i < result.length - 1; i++) {
for (let j = 0; j < result[i].length; j++) {
for (let k = i; k < result.length - 1; k++) {
for (let l = 0; l < result[k + 1].length; l++) {
if (result[i][j].position === result[k + 1][l].position) {
//merge touching array
result[i] = result[i].concat(result[k + 1]);
//remove duplicate value
result[i] = [
...new Map(
result[i].map((m: any) => [m.position, m])
).values(),
];
result[k + 1] = [];
i = 0;
j = 0;
k = i;
l = 0;
}
}
}
}
}
//remove empty array
result = result.filter(function (bl) {
return bl.length !== 0;
});
return result;