- Published on
How to Merge and Deduplicate Arrays in JavaScript
Learn two ways to merge and deduplicate two or more arrays using Javascript ES5 and ES6.
- Authors
- Name
- Mike Tsamis
Using ES5 and ES6, this tutorial will explain how to merge two or more arrays into a single array containing only the unique values from each array.
ES5 Solution
Simply use the concat() method to merge two or more arrays. Note that this method will return a new array.
const arrayA = [1, 2, 3];
const arrayB = [4, 5, 6];
const arrayC = arrayA.concat(arrayB)
console.log(arrayC);
// expected output: Array [1, 2, 3, 4, 5, 6]
ES6 Solution
You can use the destructuring assignment syntax to unpack values from arrays, or properties from objects, into distinct variables.
const arrayA = [1, 2, 3];
const arrayB = [4, 5, 6];
const arrayC = [...arrayA, ...arrayB]
console.log(arrayC);
// expected output: Array [1, 2, 3, 4, 5, 6]
TL;DR
const arrayC = arrayA.concat(arrayB)
OR
const arrayC = [...arrayA, ...arrayB]