I have the following two arrays, which is always pre-sorted:
[1,2,4,5,8]
[x,x,x,x,x]
I need to insert the missing elements and in corresponding array, put y so the output can be:
[1,2,3,4,5,6,7,8]
[x,x,y,x,x,y,y,x]
The data arrives separately but they always match size wise.
I have tried the following but am pretty sure i have over-complicated it.
function action(numbers,data){
var len=numbers.length;
if (len<=1){
return [numbers,data];
}
var new_data=[] //stores new data
var new_number=[] //stores new numbers
for(var i=1;i<len;i++){
var diff=numbers[i] - numbers[i-1];
if(diff>1){
//there is gap here
var val=0;
diff--;
for(var j=0;j<diff;j++){
val=numbers[i-1] + j +1;
new_number.push(val)
new_data.push('y')
}
//put current info after missing data was inserted
new_number.push(numbers[i])
new_data.push(data[i])
}
}
//adjust first entry
new_number.unshift(numbers[0])
new_data.unshift(data[0])
return [new_number,new_data];
}
It is not consistent and I myself can't follow it.
action([2002,2005,2007],['x','x','x']) =>[2002,2003,2004,2005,2006,2007], [x,y,y,x,y,x]
But the following is error:
action([2002,2003,2007],['x','x','x']) =>[2002,2004,2005,2006,2007], [x,y,y,y,x]
the output should have been 2002,2003,2004,2005,2006,2007 and x,x,y,y,y,x
Update
Adding an else to the diff>1 seems to fix the above errors but the solution is not elegant at all:
} else{
new_number.push(numbers[i])
new_data.push(data[i])
}