Languages
[Edit]
EN

JavaScript - merge two arrays and de-duplicate items

0 points
Created by:
Mariam-Barron
841

In this article, we would like to show you how to merge two arrays and remove duplicate items using JavaScript.

Quick solution:

// ONLINE-RUNNER:browser;

const array1 = ['A', 'B'];
const array2 = ['B', 'C'];

const array3 = array1.concat(array2)
                     .filter((item, index, array) => array.indexOf(item) === index);

console.log(array3);

 

Practical examples

1. Set based approach

In this example, we use Set based approach to prevent item duplication while adding them to the result array.

// ONLINE-RUNNER:browser;

const mergeArrays = (...arrays) => {
    const result = [];
    const blocker = new Set(); // prevents item duplication
    for (const array of arrays) {
        for (const item of array) {
            if (blocker.has(item)) {
                continue;
            }
            blocker.add(item);
            result.push(item);
        }
    }
    return result;
};


// Usage example:

const array1 = ['A', 'B'];
const array2 = ['B', 'C'];

console.log(mergeArrays(array1, array2));  // ['A', 'B', 'C']

2. Simple types approach

In this example, we use simple types to merge arrays without duplicates.

// ONLINE-RUNNER:browser;

const mergeArrays = (...arrays) => {
  	const result = [];
	const blocker = {}; // prevents item duplication
    for (const array of arrays) {
  	    for (const item of array) {
        	if (blocker.hasOwnProperty(item)) {
            	continue;
            }
          	blocker[item] = true;
          	result.push(item);
        }
    }
  	return result;
};


// Usage example:

const array1 = ['A', 'B'];
const array2 = ['B', 'C'];

console.log(mergeArrays(array1, array2));  // ['A', 'B', 'C']

Note:

This solution should be used when each item has the same type in the array, and the type is one of: boolean, number, or string.

 

See also

  1. JavaScript - merge two arrays

  2. JavaScript - remove duplicates from array

References

  1. Array.prototype.filter() - JavaScript | MDN
  2. Set() constructor - JavaScript | MDN
  3. Object.prototype.hasOwnProperty() - JavaScript | MDN

Alternative titles

  1. JavaScript - merge two arrays and remove duplicates
  2. JavaScript - merge two arrays and remove duplicate items
  3. JavaScript - getting union of two arrays
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join