given an ordered and non-repeating array arr1 = [a _ 1Magi a2recover.dagan], a subset of the array arr2 = [b _ 1rect b _ 2jn] (the order is the same as arr1)
any element ai of a given arr1, please insert it into arr2 and make sure that the order is the same as the order of arr1
for example, arr1, arr2, and arr2 now want to insert 4 into arr2
, and the result is
find an elegant algorithm
-split line-
I adopted @ hkuclion"s answer and made a small modification
let source = [3,5,4,8];
let target = [5,8];
let needle = 4;
let source_index = source.indexOf(needle);
if(source_index !== -1){
let target_index = -1;
while (source_index && target_index === -1) {
target_index = target.indexOf(source[--source_index]);
}
target.splice(target_index + 1, 0, needle);
}