skip to Main Content

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

Answers


  1. 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)
    Login or Signup to reply.
  2. 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);
    Login or Signup to reply.
  3. 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));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search