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"];
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"]
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"]
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"]
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!