Hi,
I am having some trouble understanding why one of my solutions is not working.
Construct a function
union
that takes an array of arrays and returns a new array containing all the unique elements in each subarray. Usereduce()
.
Here are my two solutions. The first one works fine, but the second one doesn’t work. It says that a.push()
and a.includes()
are not functions, which I think means that they are not being recognized as type
array. But that’s weird because concat()
works fine in the first solution.
function union(arrays) { // works fine
return arrays.reduce((a, b) => a.concat(b.filter(item => !a.includes(item))));
}
function union(arrays) { //doesn't work
return arrays.reduce((a, b) => a.push(...b.filter(item => !a.includes(item))));
}
const arr1 = [5, 10, 15];
const arr2 = [15, 88, 1, 5, 7];
const arr3 = [100, 15, 10, 1, 5];
console.log(union([arr1, arr2, arr3]));
Could someone explain why the second solution is not working?
Thank you.