Merge two arrays into JavaScript

8

Imagine that I have two arrays:

var array1 = ['abc', 'def', 'ghi'];
var array2 = ['123', '456', '789'];

I can use the .concat() function to join both arrays one after the other, for example:

array1.concat(array2) // ['abc', 'def', 'ghi', '123', '456', '789']

But how could I get to merge the values of the arrays? Is there any JavaScript function to join them so that the values of both are mixed? Example:

array1.intercalate(array2) //['abc', '123', 'def', '456', 'ghi', '789']
    
asked by anonymous 27.01.2016 / 20:20

2 answers

10

There is no native function for this, but you can build one:

var array1 = ['abc', 'def', 'ghi'];
var array2 = ['123', '456', '789'];

if(!Array.prototype.hasOwnProperty('interpolate')) {
  Array.prototype.interpolate = function(other) {
    var limit = this.length < other.length ? other.length : this.length;
    var out = [];
  
    for(var i = 0; i < limit; i++) {
      if(this.length > 0) out.push(this.shift());
      if(other.length > 0) out.push(other.shift());
    }
    
    return out;
  }
}

document.body.innerHTML = JSON.stringify(array1.interpolate(array2));

And the @Pablo alerts are worth it: If you do not have control over the use of the code and / or do not know what you're doing, create the function outside prototype (and pass another array to use instead of this ).

    
27.01.2016 / 20:37
3

You can create a simple function to solve this, I made an example here, I have not tried several cases but for your presented problem it resolves.

Example:

var array1 = ['abc', 'def', 'ghi'];
var array2 = ['123', '456', '789'];


function intercale(array1, array2) {
  var arrayResult = [];
  var total = 0;
  if (array1.length > array2.length) {
    total = array1.length;
  } else {
    total = array2.length;
  }

  for (var i = 0; i < total; i++) {
    if (array1[i]) {
      arrayResult.push(array1[i]);
    }
    if (array2[i]) {
      arrayResult.push(array2[i]);
    }
  }

  return arrayResult;
}


document.body.innerHTML = JSON.stringify(intercale(array1, array2));
    
27.01.2016 / 20:50