Seeking a method to alternate between joining two arrays of different lengths.
const array1 = ['a', 'b', 'c', 'd'];
const array2 = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const result = array1.reduce((arr, v, i) => arr.concat(v, array2[i]), []);
Upon running this code, the output is ['a', 1, 'b', 2, 'c', 3, 'd', 4]
I am aiming for
['a', 1, 'b', 2, 'c', 3, 'd', 4, 5, 6, 7, 8, 9]
const array1 = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
const array2 = [1, 2, 3, 4];
const result = array1.reduce((arr, v, i) => arr.concat(v, array2[i]), []);
When executing this code, we get
['a', 1, 'b', 2, 'c', 3, 'd', 4,'e',undefined,'f',undefined,'g',undefined]
My intended outcome is
['a', 1, 'b', 2, 'c', 3, 'd', 4, 'e', 'f', 'g']
There are two scenarios present here:
If array 1 is shorter, certain values from array 2 will be missing.
In case array 1 is longer, undefined elements will be inserted in between the merged arrays.
Looking for a solution to merge two arrays alternately regardless of their lengths.
While dealing with Swift
, simply using zip2sequence
provides an easy fix.
Is there something similar in JavaScript
?