DEV Community

Cover image for JavaScript Katas: Merge Two Arrays
miku86
miku86

Posted on

JavaScript Katas: Merge Two Arrays

Intro 🌐

Problem solving is an important skill, for your career and your life in general.

That's why I take interesting katas of all levels, customize them and explain how to solve them.


Understanding the Exercise❗

First, we need to understand the exercise!
If you don't understand it, you can't solve it!.

My personal method:

  1. Input: What do I put in?
  2. Output: What do I want to get out?

Today's exercise

Today, another 7 kyu kata,
meaning we slightly increase the difficulty.

Source: Codewars

Write a function mergeArrays, that accepts two parameters: a and b.

Given two arrays, e.g. [9, 10, 11] and ["a"], return an array that combines both arrays by alternatingly taking elements from each array in turn, e.g. [9, "a", 10, 11].

Every element in the arrays is either a string or a number.


Input: two arrays.

Output: one array.


Thinking about the Solution 💭

I think I understand the exercise (= what I put into the function and what I want to get out of it).

Now, I need the specific steps to get from input to output.

I try to do this in small baby steps:

  1. Take the 1st element of the 1st array
  2. Take the 1st element of the 2nd array
  3. Take the 2nd element of the 1st array
  4. Take the 2nd element of the 2nd array
  5. Do this [length of the longer array] amount times; in JavaScript, you get undefined, if there is no value at a specific index in an array
  6. Filter out every undefined value

Example:

  • Input: [9, 10, 11], ["a"]
  • Take the 1st element of the 1st array: 9
  • Take the 1st element of the 2nd array: "a"
  • Take the 2nd element of the 1st array: 10
  • Take the 2nd element of the 2nd array: nothing here => undefined
  • Take the 3rd element of the 1st array: 11
  • Take the 3rd element of the 2nd array: nothing here => undefined
  • Filter out every undefined value: [9, "a", 10, 11]
  • Output: [9, "a", 10, 11]

Implementation ⛑

function mergeArrays(a, b) {
  const maxLength = Math.max(a.length, b.length);
  let result = [];

  for (let i = 0; i < maxLength; i++) {
    result.push(a[i]);
    result.push(b[i]);
  }

  return result.filter((value) => value !== undefined);
}
Enter fullscreen mode Exit fullscreen mode

Result

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

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

Playground ⚽

You can play around with the code here


Next Part ➡️

Great work!

We learned how to use Math.max, filter, undefined.

I hope you can use your new learnings to solve problems more easily!

Next time, we'll solve another interesting kata. Stay tuned!


If I should solve a specific kata, shoot me a message here.

If you want to read my latest stuff, get in touch with me!


Further Reading 📖


Questions ❔

  • How often do you do katas?
  • Which implementation do you like more? Why?
  • Any alternative solution?

Top comments (3)

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"] ✅
Collapse
 
xuchunyang profile image
徐春阳
function mergeArrays(arr1, arr2) {
  if (!arr1.length) return arr2;
  if (!arr2.length) return arr1;
  return [
    arr1[0],
    arr2[0],
    ...mergeArrays(arr1.slice(1), arr2.slice(1))
  ];
}
Collapse
 
tiagojpdias profile image
Tiago Dias
const mergeArrays = (firstArray = [], secondArray = []) => {
  const result = [];

  if (firstArray.length >= secondArray.length) {
    firstArray.forEach((item, index) => result.push(item, secondArray[index]));
  } else {
    secondArray.forEach((item, index) => result.push(firstArray[index], item));
  }

  return result.filter(item => item !== undefined);
};


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

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