gvn
gvn

Reputation: 3

Two Array Result Make New Array in Javascript

This are my two data arrays:

var array1 = ["test","test1","test2"];
var array2 = ["test3","test4","test5"];

I need to concact the array to get the following result:

array3["test","test3","test1","test4","test2","test5"]

How can I archive this?

Upvotes: 0

Views: 115

Answers (4)

LF-DevJourney
LF-DevJourney

Reputation: 28529

You can find the minimal length, the process the element with index less minimal length, then attach the element from the minimal length index.

var array1 = ["test","test1","test2","test6"];
var array2 = ["test3","test4","test5"];
var array1_length = array1.length;
var array2_length = array2.length;
var minLength = Math.min(array1_length,array2_length);
var result = [];
for (var index=0; index < minLength; index++){
    result.push(array1[index]);
    result.push(array2[index]);
}
if(array1_length > array2_length){
    result = result.concat(array1.slice(index));
}
if(array2_length > array2_length){
    result = result.concat(array2.slice(index));
}
console.log(result);

Upvotes: 0

Miroslav Glamuzina
Miroslav Glamuzina

Reputation: 4557

I would recommend array.reduce() to achieve this concisely.

let array1 = ["test", "test1", "test2"];
let array2 = ["test3", "test4", "test5"];

const weaveArrays = (array1, array2) => {
  // Only allow arrays of same length
  if (array1.length === array2.length) {
    return array1.reduce((acc, v, i) => {
      acc.push(v, array2[i]);
      return acc;
    }, []);
  } else {
    console.warn('Arrays passed to "weaveArrays" must be of equal length');
    return [];
  }
}

console.log(weaveArrays(array1, array2));

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386560

You could transose the arrays and flat the result.

var array1 = ["test", "test1", "test2"],
    array2 = ["test3", "test4", "test5"],
    result = [array1, array2]
        .reduce((r, a) => a.map((v, i) => [...(r[i] || []), v]), [])
        .reduce((a, b) => a.concat(b));

console.log(result);

Upvotes: 0

Bilal Siddiqui
Bilal Siddiqui

Reputation: 3629

Considering, both arrays can have different number of elements

var array1 = ["test","test1","test2"];
var array2 = ["test3","test4","test5"];
var maxLength = Math.max(array1.length, array2.length)
var array3 = [];
for (var index=0; index < maxLength; index++) {
    if (index < array1.length)
        array3.push(array1[index]);
    if (index < array2.length)
        array3.push(array2[index]);
}
console.log(array3);

Upvotes: 1

Related Questions