0

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?

4 Answers 4

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

thanks for the help... that array1,array2 are dynamically formed one. and last array3 also dynamic then.. it's will be work
happy to help :)
0

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

Comments

0

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

2 Comments

What if array1 has 2 elements and array2 has 4 ?
In my first example, it has a check if the element exists and safely pushes the value. In my current iteration, I only allow arrays of the same length. Depends what OP wants
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.