Merge two Javascript arrays

Asked

Viewed 2,497 times

13

Imagine I have two arrays:

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

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

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

But how could you interlink the values of the arrays? Is there any Javascript function to join them so that the values of both merge? Example:

array1.intercalate(array2) //['abc', '123', 'def', '456', 'ghi', '789']
  • Do you want to follow this order anyway? array1, array2, array1, array2... etc

  • 1

    These arrays are always the same size?

  • @Randrade Yes, always this order.

  • @Guilhermelautert No. One may be smaller than the other.

4 answers

15


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

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 below are good: if you don’t have control over the use of the code and/or don’t know what you’re doing, create the function outside the prototype (and pass another array to use instead of this).

  • I was just thinking about it, and you already answered ^^

  • 1
  • @Pablo I put a guard if this method becomes standard in the future. Other than that, I don’t see much problem.

  • @bfavaretto If you own(a) the base and know well the risks, no problem, but have too much is.. in unsuspecting around. I prefer not to risk

  • @Pablo You can still leave the method unaccountable and escape the for..in. Only it will not work in pre-ES5 implementations.

  • @bfavaretto Yes... I have to manage with ES3 here...

  • 1

    @Pablo I added an alert at the end of the reply so that no one leaves here unsuspecting.

Show 2 more comments

6

Da para você criar uma função simples para resolver isso, I made an example here, I have not tested several cases but for your problem presented solves.

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));

2

Thus also works and minimizes the code:

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

function arrayIntersect(array1, array2) {

   var arr_join = [],arr = array1.map((res, i) => { 

          arr_join.push(res);
          if (array2[i]) {
             arr_join.push(array2[i]);
          }
          return arr_join;

   }); 
     return arr[0];
}
arrayIntersect(array1, array2);

0

Another small solution that seems to work well in various scenarios:

function arrayIntercale(arr1, arr2, arr3=[]) {
    
    if (arr1.length == 0) return arr3;

    arr3.push(arr1.shift());

    if (arr2.length != 0) arr3.push(arr2.shift());

    return arrayIntercale(arr1, arr2, arr3);
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.