There are multiple ways to merge arrays without duplicates in JavaScript. Commonly used methods are concat() with for Loop, Spread Syntax with Set, Set, etc.
Example merge arrays without duplicates in JavaScript
Simple example code using concat() and for Loop. The indexOf()
method returns -1 if the element is not in the array.
<!DOCTYPE html>
<html>
<head>
<script>
const arr1 = [1, 2, 3];
const arr2 = [2, 3, 5];
// merge two arrays
let arr = arr1.concat(arr2);
let uniqueArr = [];
// loop through array
for(let i of arr) {
if(uniqueArr.indexOf(i) === -1) {
uniqueArr.push(i);
}
}
console.log(uniqueArr);
</script>
</head>
</html>
Output:
Using Spread Syntax and Set
The array is converted to Set
and all the duplicate elements are automatically removed.
<script>
const arr1 = [1, 2, 3];
const arr2 = [2, 3, 5];
// merge two arrays
let arr = [...arr1, ...arr2];
// removing duplicate
let uniqueArr = [...new Set(arr)];
console.log(uniqueArr);
</script>
Do comment if you have any doubts or suggestions on this JS merging array topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version