-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.

3 Answers3

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)
Mina
  • 14,386
  • 3
  • 13
  • 26
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

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));
Learn-code
  • 162
  • 8