Hi, this is from the Intermediate Algorithms Sorted Union challenge. I actually got it to work with nested for loops, but I banged my head against the challenge with this forEach in a while loop for a time. I still don’t understand why it won’t work–gives me a Type error notice.
It seems to come down to the args[counter].forEach() part. I console out args[counter] in the loop, outside the loop, use Array.isArray() on it… It seems to be fine until I actually put it in this context.
function uniteUnique(arr) {
let args = [...arguments];
let newArr = args[0];
let counter = 1;
while (counter <= args.length) {
args[counter].forEach(item => {if ( newArr.indexOf(item) === -1) {newArr.push(item);}} );
counter++;
}
return newArr;
}
console.log(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/84.0.4147.105 Safari/537.36.
It seems like that the .forEach() cannot read an undefined value. Then looking at it, it’s trying to grab the value of args at the nth of [counter].
If you actually console.log() it, it shows that it crashed after the counter reached number 3, then it crashed. This is because on your while loop you have counter <= args.length which means it will go until the length of the arguments.
From previous lesson we learned that JS has a 0 indexed array system. that means, the first Item in the array is indexed as 0. so starting the counter at 1, will SKIP the very first item.
What you want to do is change the change the logic of counter <= args.length into counter < args.length.