How to merge two arrays into a unique array in JavaScript

Published on

The easiest way to get the union of two arrays is to use a combination of the spread operator and the Set object. In the example below the name Beth appears in both arrays but in our union array it only appears once. Within the Set object we spread the contents of the two team arrays to merge them together then we spread the resulting Set object into our new array to create an array of unique values.

const teamOneNames = ['Ben', 'Beth', 'Karl'];
const teamTwoNames = ['Leah', 'Ted', 'Beth'];

const union = [...new Set([...teamOneNames, ...teamTwoNames])];

console.log(union);
//  ['Ben', 'Beth', 'Karl', 'Leah', 'Ted']

This is also possible with the help of a utility library like lodash. It has a handy union function for exactly this purpose.

const teamOneNames = ['Ben', 'Beth', 'Karl'];
const teamTwoNames = ['Leah', 'Ted', 'Beth'];

const union = _.union(teamOneNames, teamTwoNames);

console.log(union);
//  ['Ben', 'Beth', 'Karl', 'Leah', 'Ted']