Problems with js array operation

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);
}

Mar.10,2021

or modify the way of comparison in dichotomy

let arr1 = [3,5,4,8] 
let arr2 = [5,8] 
let indexMap = {}
for(let i=0;i<arr1.length;iPP){
    indexMap[arr1[i]] = i
}
insert(arr2,0,arr2.length,4)
console.log(JSON.stringify(arr2))

function insert(arr,l,r,num){
    if(l==r){
        arr.splice(l, 0, num)
        return
    }
    let index = parseInt((r+l)/2)
    if(indexMap[arr[index]]<indexMap[num]){
        insert(arr,index+1,r,num)
    }else{
        insert(arr,l,index,num)
    }
}

try the following code

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 = source_index? target.indexOf(source[source_index - 1]) + 1:source_index;
    target.splice(target_index, 0, needle);
}

 

since it is orderly. In fact, it doesn't matter whether there is arr1 .

in order, you just use dichotomy to put ai into arr2 .

MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1b35a2a-2bfa1.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1b35a2a-2bfa1.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?