I solved it in this way, but i think if the array given is more than 3 elements it's going to be a wrong answer. what's your opinion?

Tell us what’s happening:

Your code so far


function uniteUnique(arr, ...args) {

let newArr = [...arr]

  for (var a = 0; a < args.length; a++) {
    for (var b = 0; b < args[a].length; b++) {
      
      if (args[a][b] !== arr[0] && args[a][b] !== arr[1] && args[a][b] !== arr[2]) {
        newArr.push(args[a][b]);
      } 
    }
  }

return newArr;
}

console.log(uniteUnique([1, 3, 2, 4], [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/83.0.4103.116 Safari/537.36.

Challenge: Sorted Union

Link to the challenge:

Yes, this only works with 3 arrays, as you mentioned. My solution to this question, which works with any amount of arrays, can be seen below

const uniteUnique = (...arr) => [...new Set([...arr].flat())];

To go over it step by step

(...arr)

Take all arguments passed into this function using the spread operator, and put them inside the

arr

variable. Then, inside the function

[...arr]

Spread them into an array like this

[...arr].flat()

Flatten the array using the flat() function

new Set([...arr].flat())

Since we want to have only the unique values, a set is perfect for us. You can think of a set like an array which can have unique values only.

But since the output must be an array, not a set, we must convert it back to an array

[...new Set([...arr].flat())];

And so we just spread the contents of the set inside an array. That’s it, we now have a combined array of unique values. This works with any amount of arrays. And also, if the arrays are nested deeper, you can make use of .flat(2) or .flat(3) and so on, specifying the amount of depth.

your code can work with any number of arrays in args, the issue instead is in this line. What if arr has a different number of elements? what if there is a 5 both in args[0] and in args[1]? you are also not checking arr[3]

in fact your code returns [ 1, 3, 2, 4, 5, 4 ], you should only have one single 4 in there

you may want to think of checking the array you are building with something like includes