JavaScript Katas: Merge Two Arrays
miku86
Posted on August 20, 2020
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:
- Input: What do I put in?
- 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:
- Take the 1st element of the 1st array
- Take the 1st element of the 2nd array
- Take the 2nd element of the 1st array
- Take the 2nd element of the 2nd array
- 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 - 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);
}
Result
console.log(mergeArrays([9, 10, 11], ["a"]));
// [9, "a", 10, 11] ✅
console.log(mergeArrays([1], ["a", "b"]));
// [1, "a", "b"] ✅
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?
Posted on August 20, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.