Array.prototype.reduce() not working how I expect it to

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. Use reduce().

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.

With the second one, you’re returning a number as the new value of the accumulator, rather than an array, and you can’t push to a number

1 Like

Thank you, @DanCouper

Apparently that’s just a JS thing. So for some reason, when I return arr1.push(arr2), it returns the length of the new array, not the array, itself.

If I do this:

arr1.push(arr2);
return arr1;

…it works, for some reason. Weird.

Push in Rust doesn’t return the array: Vec in std::vec - Rust

No return value for Python either: 5. Data Structures — Python 3.11.3 documentation

You are mutating the array with push, so there is no need to return another reference to the array itself. I’m not sure which languages actually return the array itself after a push? It’s not really an operation you would insert into chaining.

1 Like

@JeremyLT

Dang. Okay. Yeah, that makes sense.

Thank you for the insight.

1 Like