Intermediate Algorithm Scripting - Sorted Union

Tell us what’s happening:
in the given challenge, we have to write a function that takes arrays as input and return a combined array having unique values in the order they were passed as arguments.

in my code, I first used the spread operator and argument object to combine the arrays and then used set to filter out the unique values . however I’m not getting the desired result.
please help me with this…thank you.

Your code so far

function uniteUnique(arr) {
  let arr1 = [...arguments];
  let mergearr = new Set(arr1);
  return [...mergearr];

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

Your browser information:

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

Challenge: Intermediate Algorithm Scripting - Sorted Union

Link to the challenge:

What is in arr1? Log it out and check.

(also, arr1 is a not so great variable name. Also, you should use const for array declarations when possible)

thank you for helping out I’ll keep in mind next time coding
but could you please elaborate what do you mean by “what is in arr1”?..iit obviously returns the arguments provided in function call with their indices.

“Obviously” is the enemy of a debugging mindset. Check the actual contents of arr1 via console.log(). The contents are not individual elements!!

1 Like

you are correct. The output is an array containing all the arrays individually. It would be great help if you could tell me what should be my desired result for the set operator to work on it.
P.S.:- i’m new to coding… sorry if my questions come out to be annoying.

console.log() is magic, honestly.

function uniteUnique(arr) {
  const args = [...arguments];
  console.log("args      :", args);
  const argsSet = new Set(args);
  console.log("argsSet   :", argsSet);
  console.log("...argsSet:", [...argsSet]);
  return [...argsSet];

Here I get

args      : [ [ 1, 3, 2 ], [ 5, 2, 1, 4 ], [ 2, 1 ] ]
argsSet   : Set(3) {1,3,2, 5,2,1,4, 2,1}
...argsSet: [ [ 1, 3, 2 ], [ 5, 2, 1, 4 ], [ 2, 1 ] ]

So it looks like the items fed into the Set are the individual items in the args array.

So really, your question is, how do you “flatten” args into something that looks like [1, 3, 2, 5, 2, 1, 4, 2 ,1]. There are lots of potential approaches. What might work?

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