Having two pre-sorted arrays as shown below:
[1,2,4,5,8]
[x,x,x,x,x]
The goal is to fill in the missing elements with 'y' in the corresponding array, resulting in:
[1,2,3,4,5,6,7,8]
[x,x,y,x,x,y,y,x]
Although the data arrives separately, they always have matching sizes.
An attempt was made to achieve this task but it seems a bit complex:
function action(numbers,data){
var len=numbers.length;
if (len<=1){
return [numbers,data];
}
var new_data=[]
var new_number=[]
for(var i=1;i<len;i++){
var diff=numbers[i] - numbers[i-1];
if(diff>1){
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')
}
new_number.push(numbers[i])
new_data.push(data[i])
}
}
new_number.unshift(numbers[0])
new_data.unshift(data[0])
return [new_number,new_data];
}
Despite some inconsistencies in the function, it is not completely clear.
action([2002,2005,2007],['x','x','x']) =>[2002,2003,2004,2005,2006,2007], [x,y,y,x,y,x]
However, there are still errors like the one shown below:
action([2002,2003,2007],['x','x','x']) =>[2002,2004,2005,2006,2007], [x,y,y,y,x]
The expected output should have been 2002,2003,2004,2005,2006,2007 and x,x,y,y,y,x
Update:
Adding an else statement after the diff>1 condition seems to fix the previous errors, although it's not the most elegant solution:
} else{
new_number.push(numbers[i])
new_data.push(data[i])
}