Javascript: How To Merge 2 Arrays
Array manipulation is a hot topic in JavaScript since it is a weakly typed programming language. In an interview, you could be asked to write a program that merges the 2 arrays namely arraya1 and arraya2. In this article, I would demonstrate how 2 arrays can be merged together. Lets dive in…
Step 1: Declare the 2 arrays in different variables.
Step 2: Write a function that accepts 2 arrays as parameters: Here, we write a function (mergerArray) that accepts 2 inputs/parameters. The other variables in are created for the below purposes:
arrayHome: This would accept all elements of the first and second array when merged. Elements would simply be pushed into this empty array.
arrayItems1: This is the first index of the first array parameter.
arrayItems2: This is the first index of the second array parameter.
otherItems1 and otherItems 2 would be discussed in step 4.
Step 3: Write a condition to check if there are no elements in array1 or array2 i.e. an empty array [ ]. array1 should just return array2 if empty or vice versa.
Step 4: Remember our variables otherItem1 and otherItem2 in step2? We initialized those variables because of the if statement in our while loop.
In the while loop above, we are checking if we have items in arrayItems1 or arrayItems2 (these are still the first indexes of our input arrays for now). To avoid a situation where we have no input or undefined, we need to write an if statement that checks if we do not have elements in arrayItems2 or the first index of arrayItems1 is less than the first index of arrayItems2, we simply push those indexes to the arrayHome. For arrayItems1 and arrayItems2, we also need their other elements not just their first indexes, so we increment otherItems1 and otherItems2 (1, 2, 3 …).
Thanks for reading.