JS join arrays with replacement

You could do the following:

var arr1 = ["a", "b", "c"];
var arr2 = ["k",undefined,"l","m","n"];
var arr3 = [];


function join_arrays(arr1,arr2){
arr3 = arr2;
var i = arr3.indexOf(undefined);
while(i !=- 1){
    arr3[i] = arr1[i];
    i = arr3.indexOf(undefined);
    }
return arr3;
}

However there is a little caveat here, as far as my testing in JSBin showed me, which is that you have to have set the empty values that are gonna be replaced to undefined explicitly as I did in my example. If this is not optimal for you, there might be a better way than what I showed here.

Hopefully this runs faster than your code, as it will only go through the loop as many times as needed to do the replacements and will fill arr3 with arr2 right away.

UPDATE:

Bear in mind that, while the above function works, it is unsafe because when the second array has empty elements in an index that is not present in the first one, it will cause an error. Therefore you could do something like this:

function join_arrays(arr1,arr2){
arr3=arr2;
var i = arr3.indexOf(undefined);
while(i!=-1 && i<arr1.length){
    arr3[i]=arr1[i];
    i=arr3.indexOf(undefined);
    }
return arr3;
}

So for var arr2 = ["k",undefined,undefined,"l","m","n",undefined] result will be ["k", "b", "c", "l", "m", "n", undefined] with this method, instead of getting an error or infinite loop!

Browse More Popular Posts

Leave a Comment