forEach question

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.

Challenge: Sorted Union

Link to the challenge:

Hello~!

Check the conditions of your while loop. What is the value of args.length?

1 Like

Hey @CactusWren2020,

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.

Hope this helps :slight_smile:

1 Like

This part isn’t necessary, as they’ve initialised newArr with the value of args[0] :slight_smile:

1 Like

Arrg, you are right about the <= problem. I should have caught that, thanks!

I did have a reason for starting from 1, though; it’s because the first args is already in the target array.

Thanks all!

function uniteUnique(arr) {
	let args = [...arguments];
	let newArr = [];
	args.forEach(nest => {
		nest.forEach(nested =>{
			if(!newArr.includes(nested))newArr.push(nested);
		})})
console.log(newArr);
}
uniteUnique([1, 3, 2], [5, 2, 1, 4], [2, 1]);