Home > Web Front-end > JS Tutorial > How to Merge Two JavaScript Arrays and Keep Only Unique Items?

How to Merge Two JavaScript Arrays and Keep Only Unique Items?

Mary-Kate Olsen
Release: 2024-12-24 05:40:19
Original
249 people have browsed it

How to Merge Two JavaScript Arrays and Keep Only Unique Items?

Merging Two JavaScript Arrays with Unique Items

Merging arrays is a common task in programming, but it can become slightly more complex when you want to ensure that the resulting array contains unique items only. In this article, we will explore how to merge two JavaScript arrays while preserving their original order and eliminating duplicate elements.

Consider two JavaScript arrays:

var array1 = ["Vijendra", "Singh"];
var array2 = ["Singh", "Shakya"];
Copy after login

Our goal is to create a new array, array3, that contains the unique elements from both array1 and array2. The correct output should be:

["Vijendra", "Singh", "Shakya"]
Copy after login

To achieve this, we can leverage a combination of JavaScript's built-in array methods:

Simple Array Merging

To simply merge the two arrays without removing duplicates, we can use the concat() method:

var array3 = array1.concat(array2);
console.log(array3); // ["Vijendra", "Singh", "Singh", "Shakya"]
Copy after login

This will create a new array containing all the elements from both array1 and array2. However, it does not eliminate duplicates.

Merging with De-duplication

To filter out duplicates while merging the arrays, we can use a combination of the reduce() and includes() methods:

var array3 = array1.reduce((acc, curr) => !acc.includes(curr) ? acc.concat(curr) : acc, []);
var array4 = array3.concat(array2.filter(x => !array3.includes(x)));
console.log(array4); // ["Vijendra", "Singh", "Shakya"]
Copy after login

In this code, we use reduce() on array1 to create a new array that only contains unique elements. Then, we concatenate this new array with the filtered elements from array2, ensuring that duplicates are removed.

The above is the detailed content of How to Merge Two JavaScript Arrays and Keep Only Unique Items?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template