Search code examples
javascriptdictionaryforeacharray-algorithms

Getting 1 item from each array and concating


Ok so basically we have 2 arrays like this

Array1=[1, 3, 5, 7]
Array2=[0, 2, 4, 6]

and i want to unite them into one array like

Array3=[0, 1, 2, 3, 4, 5, 6, 7]

is there an algoithm for that? Or like a built in function? I mean i tried it but couldnt make it


Solution

  • You can merge the two using .flatMap() on one of your arrays, and grabbing the associated value from your other array using the index:

    const arr1 = [1, 3, 5, 7];
    const arr2 = [0, 2, 4, 6];
    
    const res = arr2.flatMap((num, i) => [num, arr1[i]]);
    console.log(res);