How to use reduce and includes In Javascript
Using reduce and includes, combine two arrays and build a new array with unique elements. The reduce method iterates through the combined array, adding each element to the accumulator if it doesn’t already include it, ensuring no duplicates.
Example: In this example we combines array1 and array2 using concat, then uses reduce to create a union array containing unique elements by checking for duplicates with includes.
const array1 = [1, 2, 3];
const array2 = [3, 4, 5];
const combinedArray = array1.concat(array2);
const union = combinedArray.reduce((acc, item) => {
if (!acc.includes(item)) {
acc.push(item);
}
return acc;
}, []);
console.log(union);
Output
[ 1, 2, 3, 4, 5 ]
How to find every element that exists in any of two given arrays once using JavaScript ?
In this article, we will learn how to find every element that exists in any of the given two arrays. To find every element that exists in any of two given arrays, you can merge the arrays and remove any duplicate elements.
Table of Content
- Using Set
- Using loop
- Using filter() and concat()
- Using reduce and includes