How to use reduce() and includes() In Javascript
Using reduce() and includes(), initialize the accumulator with one array, then iterate over the other array. If the value is not already in the accumulator, add it. This method ensures uniqueness while computing the union.
Example:
const array1 = [1, 2, 3];
const array2 = [3, 4, 5];
const union = array1.reduce((acc, val) => {
if (!acc.includes(val)) {
acc.push(val);
}
return acc;
}, array2.slice());
array2.forEach(val => {
if (!union.includes(val)) {
union.push(val);
}
});
console.log(union);
Output
[ 3, 4, 5, 1, 2 ]
How to compute union of JavaScript arrays ?
Given two arrays containing array elements and the task is to compute the union of both arrays with the help of JavaScript.
These are the methods to solve this problem which are discussed below:
Table of Content
- Using the spread operator and set
- Using the push() method
- Using filter() and concat() Method
- Using Underscore.js _.union() Function
- Using reduce() and includes()