DEV Community

Discussion on: JavaScript Katas: Merge Two Arrays

Collapse
 
pentacular profile image
pentacular

There's no good reason to limit ourselves to two, and no particularly good reason to post-filter.

const mergeArrays = (...arrays) => {
  const result = [];
  const length = Math.max(...arrays.map(array => array.length));
  for (let nth = 0; nth < length; nth++) {
    for (const array of arrays) {
      const item = array[nth];
      if (item !== undefined) {
        result.push(item);
      }
    }
  }
  return result;
}

console.log(mergeArrays([9, 10, 11], ["a"]));
// [9, "a", 10, 11] ✅

console.log(mergeArrays([1], ["a", "b"]));
// [1, "a", "b"] ✅