My Array.prototype.reduce() is converting my accumulator into a string, how do i make it not do that?

function diffArray(arr1, arr2) {
  const sourceArr = arr1.concat(arr2);

  return sourceArr.reduce((outArr, item) => {
    return typeof outArr;
  }, []);
}

const test = diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]);
console.log(test)

i am currently working on the “diff two arrays” challenge in FCC but im pretty sure the problem is just JS quirks, if i try to apply array methods on the accumulator it wont recognize them, so i logged the type of the accumulator, why the hell does it say string? what happened?

You have initialized the accumulator as an array (that is good). However, in your return statement, you are just returning a string "object" (due to using typeof on outArr) in the first iteration. At the start of the second iteration, the accumulator is a string, which is why you would get "string" for typeof outArr.

As far as making sure the accumulator remains an array throughout all iterations, then you need to make sure you are returning an array.

1 Like

thanks, but im pretty sure i tried just treating it as a normal array, for example if i wanted to push every element of sourceArr:

function diffArray(arr1, arr2) {
  const sourceArr = arr1.concat(arr2);

  return sourceArr.reduce((outArr, item) => {
    return outArr.push(item);
  }, []);
}

const test = diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]);
console.log(test)

this returns an error, what am i missing?

edit: push returns the length of the array after the push operation, not the array or the item being pushed, i am fuming with rage but at least i figured it out, thanks for the help!

1 Like

The reason you are getting an error is because push() returns the length of the array once an item is added to it, witch is transforming outArr, in the subsequent iterations, into a number, since that is what is effectively being returned by the callback. You can get around this by placing your return in another line, making sure you are solely returning outArr.

do:

outArr.push(item);

and then:

return outArr;

I hope this solves the issue. Forgive any mistakes. It is the first time I contribute here and english is not my first language.

2 Likes

speaks in perfect english and solves my problem if i hadnt already solved it on my own

proceeds to apologize
dont worry bro your english is epic you should post more :).

1 Like

Glad all end well. Thanks for the compliment :sweat_smile:

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.