Search code examples
javascriptarraysundefined

JavaScript - Merge two arrays with different sizes


I have two arrays:

var array1= [1,3,5,7,9,11]
var array2= [undefined,4,6]

I need to merge one element of the array1, then one element of the array2, etc. This is my code:

function mergeArrays(array1, array2){
    var array3 = []; 
    maxlength = Math.max(array1.length, array2.length);

for(i=0;i<maxlength;i++){   
    array3.push(array1[i]);  
    array3.push(array2[i]);
}      
    return console.log(array3);
}

The output now is:

array3 = [1,undefined,3,4,6,7,undefined,9,undefined,11,undefined]

I need the output to be:

array3 = [1,undefined,3,4,6,7,8,11]

I mean, I can't use ( != undefined), because if I have an undefined in the middle of the array it has to be there.


Solution

  • You are not placing a check for the length of shorter array. Your function is fetching a value which is higher than the length of the array, hence, extra undefined. This should do the job

    var array1 = [1, 3, 5, 7, 9, 11];
    var array2 = [undefined, 4, 6];
    
    function mergeArrays(array1, array2) {
      var array3 = [];
      maxlength = Math.max(array1.length, array2.length);
    
      for (i = 0; i < maxlength; i++) {
        if (i < array1.length) array3.push(array1[i]);
        if (i < array2.length) array3.push(array2[i]);
      }
      return console.log(array3);
    }
    
    mergeArrays(array1, array2);