Sorted Union - chaining .unshift to args AND does not pass unique value requirement

Sorted Union - chaining .unshift to args AND does not pass unique value requirement
0

#1

Tell us what’s happening:
Hello,

  1. I can’t chain .unshift(arr) to the end of args and was wondering why. The .concat() method seems to work fine so I’m a little confused as to why .unshift() wouldn’t work as well.

  2. I wanted to see what happened by changing the value in one of the 2d arrays:

uniteUnique([1, 3, 2], [1, [5]], [2, [3]]);
//returns [1, 3, 2, [5], [3]] which doesn’t pass the requirement to return only unique values

Removing the brackets from the numbers seem to allow the filter to iterate over the value which leads me to suspect the filter() isn’t even iterating over the 2d arrays.

Can someone tell me what is going on? Do I need to further flatten the arrays? Or is this simply a bug of filter?

Also, all the code hint solutions behave the same way.
Your code so far


function uniteUnique(arr) {
  var args = Object.values(arguments);
  args = args.reduce((accu, curr) => {
    return accu.concat(curr);
  }).filter(x => {
    if (!arr.includes(x)){
       return x
    }
  });
  return arr.concat(args)
}

uniteUnique([1, 3, 2], [1, [5]], [2, [3]]);

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/sorted-union/


#2
  1. Read up on what unshift returns. It is not an array.
  2. [1, 3, 2, [5], [3]] - those are all unique values. 3 is not the same type of thing as [3].

Regarding 2: This is confusing, particularly as it would be generally expected that a union would be a union of the same type of thing. Also note that technically [[1],[1],[1],[1],[1]] should be a perfectly reasonable, correct output in this challenge which just seems…wrong. (one object !== another object, unless they are references to the exact same object). I’m sure in a previous iteration, this challenge was all numbers, and if I’m right on that I don’t quite get why it was changed


#3

Hi Dan,

Thanks so much. Things are a bit clearer now.

  1. unshift() returns the new length when it is chained to args. So what I did was write out:
    args.unshift(arr); return args;

This returned the correct result.

  1. I think the gist of what you said is that in [1, 3, 2, [5], [3]], 3 and [3] are not the same because they are two different objects not referencing the same object.

#4
  1. With unshift, yes, you can do that. concat is maybe a bit easier to think about - it just creates a new array by adding a value onto an existing array, but the unshift way, mutating the array, is fine.

  2. No, no. Look at the two things: 3 and [3]. These are not the same type of thing: nothing to do with references, they are clearly completely different things.