Image for post

If you are reading this post, you might be puzzled as to how so-called “simple problems” can turn into nightmares. Anyone working on JavaScript is aware of the fact that arrays need to be merged some time or another. You are bound to face a situation where you have two or more arrays that need to be merged. This is a trivial problem that has multiple solutions so let’s look into three different ways to solve this issue.

Watch my YouTube Video for a live demo:

The Traditional “For” Loop.

The traditional method (and the most common method) involves two or more for-loops based on the number of arrays.

Pseudocode to run for loops and merge arrays:

Iterate through each item in array

Check if array item is found in the “merged_array” or not. Use “indexOf()” to judge if the array item is present.

If the array item is not present, indexOf() will return “-1”. Then, merge the item into “merged_array”.

if the array item is present, indexOf() will return it’s position in the “merged_array”. Hence, do nothing.

Repeat steps 1 to 4 on all the arrays to be merged.

Time complexity Computation

For merging two arrays using for loops, the time complexity would be as follows:

_To iterate through an array, with “n” items: _Big O(n)

_To execution of indexOf method: Big O((n-1)+(n-2)+(n-3)……+1): _Big O(n)

To Execution of indexOf method, “n” times: Big O(n)*n: Big O(n²)

_Overall time complexity: _Big O(n²)

The code

let array1 = ['a','b','c']

let array2 = ['c','c','d','e'];
let array3 = [];
for(let i=0;i<array1.length;i++){
  if(array3.indexOf(array1[i]) == -1)
     array3.push(array1[i])
}
for(let i=0;i<array2.length;i++){
  if(array3.indexOf(array2[i]) == -1)
     array3.push(array2[i])
}

ES5 Solution

The ES5 solution replaces the “for loops”. Instead, it makes use of built-in array functions like concat and filter.

_concat() _can be used to merge multiple arrays together. But, it does not remove duplicates.

_filter() __is used to identify if an item is present in the “merged_array” or not. Just like the traditional for loop, filter uses the __indexOf() _method to judge the occurrence of an item in the merged_array.

#interview-questions #javascript #code-optimization #merge #arrays

How to merge arrays without duplicates in JavaScript?
14.70 GEEK