I have a target
array, say: [A, C, E, F, H]
.
I have another array toMerge
that needs to be merged into target
, say: [B, D, G, I]
.
I also have an integer array that tells the indices of target array where toMerge
items will be finally merged at, say: [1, 3, 6, 8]
.
I need a function that will merge toMerge
array into target
in-place, at indices specified by the indices
array so that target
eventually looks like
[A(0), B(1), C(2), D(3), E(4), F(5), G(6), H(7), I(8)]
I tried using inbuilt array splice functions to iterate over indices array and splice(add) each at each index. Something along the lines:
for (let i = 0; i < indices.length; i++) {
target.splice(indices[i], 0, toMerge[i]);
}
I am looking for any solution that can do it more efficiently and elegantly.
It gets trickier if the indices
array is unsorted or worse – reverse-sorted! For e.g.,
toMerge: [I, G, D, B]
indices: [8, 6, 3, 1]
after applying the above algorithm, target
ends up being:
target: [A, B, C, E, D, F, H, I, G]
One solution to this is to sort the indices
array in non-decreasing order along with the toMerge
array ensuring the sequence is honored, further complicating things.
2
Answers
Unsorted indices + absolute
If you are working with unsorted indices: you would have to "zip" (need to first
transpose
) the array to be merged and its corresponding indices. Once you have a matrix of[index, value][]
sorted, you can perform an in-order splice.Original response
If you are working with absolute indices (as you are), you can insert the items in-order; but if you use relative indices, you need to reverse the insertion.
Absolute merge
Relative merge
Thinking on sorted, reverse-sorted, and a possibility of unsorted list
toMerge
, at first we need to merge thetoMerge
with theindices
list and sort, then we can merge these values with thetarget
list, for example:Or in a resumed way: