I have a list of arrays where the same item may appear in different lists (but not in the same list). I'm trying to sort the arrays so that matching items have the same index in all the arrays. I'm also trying to fill the empty spots where possible, but it's fine if some positions remain undefined.
Conditions
- All dupes are always sequential, so if an element is a dupe, there's for sure a copy in the previous array.
- Each item can occur only once per array (the dupes are only in different arrays)
- The foo arrays may have different lenghts
- The foo array always exist, in the worst case it's empty.
- The order in the foo array is not relevant as long as the goal is accomplished.
- The wrapper array can't be sorted.
Input
const myWrapper [
{ foo: [] },
{ foo: ['A', 'B', 'C', 'D'] },
{ foo: ['X', 'A', 'E', 'C'] },
{ foo: ['X', 'F', 'C', 'G', 'H'] },
{ foo: ['C'] }
];
Desired output
const myWrapper [
{ foo: [] },
{ foo: ['B', 'A', 'C', 'D'] },
{ foo: ['X', 'A', 'C', 'E'] },
{ foo: ['X', 'F', 'C', 'G', 'H'] },
{ foo: [undefined, undefined, 'C'] }
];
Is there a neat way to achieve this?
My attempt, sorting from the right and using a tmp variable to swap the items. This doesn't seem to work well as the following position sometimes move previous items messing with the order set in the previous iteration.
let tmp;
myWrapper.forEach((item, wrapperIndex) => {
item.foo.forEach((currentFoo, fooIndex) => {
// Search for match in the previous foo
if(myWrapper[wrapperIndex - 1]) {
const prevFoo = myWrapper[wrapperIndex - 1].foo;
const prevIndex = prevFoo.indexOf(item);
if (prevIndex >= 0 && prevIndex !== fooIndex) {
tmp = prevFoo[fooIndex];
prevFoo[fooIndex] = prevEvents[prevIndex];
prevFoo[prevIndex] = tmp;
}
}
});
});
Edit: the issue is also that the loop does other operations on the single items (which are objects really, I used strings to simplify), so I can't move from the right (current items).
The output is rendered via Angular using 2 nested *ngFor so the final result has to maintain this array structure.