Sorted Union not uniting

Hi everyone,

I was wondering if someone could help me work out why my code doesn’t work. I’ve been scratching my head on this for a while now. Wherever I console.log it the result variable just remains as the contents of arr[0] with no values from the other arrays concatenated onto it. I tried .push as well and still nothing was happening.

Your code so far


function uniteUnique(...arr) {
let result = [].concat(arr[0]);
for(let i=1; i >= arr.length; i++){
    result.map(input=>
              {if(arr[i].indexOf(input) == -1)
              {result.concat(arr[i].indexOf(input))}
              console.log(result)})};
    console.log(result);
return result;}

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

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:

First of all, you should not be using the map method in this manner. The map method returns a new array based on the callback. Instead, you are using the map method as the forEach method. Just use the forEach method instead.

Also, keep in mind that concat returns a new array. You are not always assigning the result of your concat to anything.

Hi Randell, thank you for your assistance. I was using the map and concat because I didn’t want to alter the original array, I was trying to keep the principle of functional programming taught in the previous segment but I realise now I’d have been creating a mess of lots of different new arrays and not retrieving values from them. Thanks you for pointing that out, I’ll be careful to use map and forEach when each is more suitable in the future.

I switched map to forEach and concat to push but got exactly the same result as before. Weirdly it seems that the part of my code which combines the arrays isn’t getting read at all as I tried declaring a new variable in that part at one point and was told when I console.logged it that the variable wasn’t declared. So maybe my function is returning before that point?