Member-only story

JavaScript — 3 ways to combine an array and remove its duplicates

Marika Lam
1 min readOct 27, 2022

--

Method #1: for loop

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])}return array3;

Overall time complexity: Big O(n²)

Method #2: using concat and filter (ES5 solution)

let array1 = ['a','b','c']let array2 = ['c','c','d','e'];let array3 = array1.concat(array2);array3 = array3.filter((item,index)=>{return (array3.indexOf(item) == index)})

Overall time complexity: Big O(n²)

Method #3: destructure the arrays, in to a new set (ES6 solution)

let array1 = ['a','b','c']let array2 = ['c','c','d','e'];let array3 = array1.concat(array2);array3 = [...new Set([...array1,...array2])]

Overall time complexity, if n>m: Big O(n)

So which is best?

The solution offered by ES6, is the simplest and is the least expensive one. With a time complexity of O(n), this is the most ideal choice for any merging two, or more arrays without duplicates.

--

--

No responses yet