-1

I've been trying to get a specific result to this issue but couldn't find an answer that suits it, so I'm working with 2 arrays of the same length:

arr1 = [value1,value2,value3]

arr2=[otherValue1,otherValue2,otherValue3]

how can I concat the 2 arrays by the order of the index?

expected result = [value1,otherValue1,value2,otherValue2,value3,otherValue3]

Sorry if this question is a duplicate, but couldn't find my expected result by using concat or splice.

4
  • Can you expect that both arrays are the same length? Commented Oct 17, 2022 at 21:11
  • also: zip two arrays Javascript Commented Oct 17, 2022 at 21:19
  • @pilchard the two of them completely answer my question. Thanks for the pointers Commented Oct 17, 2022 at 21:27
  • @Miguel Sanchez please check my approach and let me know, if it helped you Commented Oct 17, 2022 at 21:43

3 Answers 3

2

You can use reduce

const arr1 = ['value1', 'value2', 'value3']

const arr2 = ['otherValue1', 'otherValue2', 'otherValue3']

const result = arr1.reduce((acc, item, index) => [...acc, item, arr2[index]], [])

console.log(result)

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

Comments

1

let arr1 = ['value1','value2','value3'];

let arr2=['otherValue1','otherValue2','otherValue3'];

let result = [];

for(let i =0; i<arr1.length; i++){
  result.push(arr1[i]);
  result.push(arr2[i]);
}

console.log(result);

1 Comment

Super simple, I don't know how I couldn't think of this.
1

let arr1 = ['value1','value2','value3'];

let arr2=['otherValue1','otherValue2','otherValue3'];


const merge = (arr1, arr2) => {
  const res= [];
  arr1.forEach((arr,i) => 
    res.push(`${arr}`,`${arr2[i]}`)
    );
    return res;
}

console.log(merge(arr1,arr2));

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.