# Sorted Union Exercise--Why can't I use concat in my for Loop?

Hi all,
Quick question. I tried solving the problem in 2 different ways. One of them was with a for loop. I tried using concat inside my for loop (trying to add numbers to an arr), but it wouldn’t work. I was trying to understand the difference between using push() and concat () for this particular case.
My second option was with filter, and concat did work.
Any guidance is greatly appreciated.

Using For Loop

``````function uniteUnique(arr) {
let allArgs = [...arguments];
let finalArr = allArgs.shift();//keeps fist arr
for(let i =0; i<allArgs.length; i++){
for (let j = 0; j < allArgs[i].length; j++){
if(!arr.includes(allArgs[i][j])){
finalArr.push(allArgs[i][j]);
}
}
}
return finalArr;
}
uniteUnique([1, 3, 2], [5, 2, 1, 4], [2, 1]);
``````

Using Filter()

``````function uniteUnique(arr) {
let allArgs = [...arguments];
let finalArr = allArgs.shift();
let joinRemainingArrs = Array.prototype.concat(...allArgs);
//console.log(joinRemainingArrs);
let noDuplicates = joinRemainingArrs.filter(x=> !arr.includes(x)? x: null);
return finalArr.concat(noDuplicates);
}
uniteUnique([1, 3, 2], [5, 2, 1, 4], [2, 1]);
``````

When in doubt, MDN

Specifically, this sentence is critical

This method does not change the existing arrays, but instead returns a new array.

1 Like

Thank you so much. Will keep note that concat doesn’t change initial array.
With that in mind, I’m still not sure I understand why I can’t use concat inside my for loop.
What am I not seeing?
When using a for loop, do we always have to change the original array?

You don’t need to change the original array - in fact, I recommend against doing that.

But `push()` changes the array being referenced while `concat()` does not, so they cannot be used interchangeably. With `concat()` you need to save the result of the method call in a variable or return it. Otherwise, the result is just thrown away and has no effect.

1 Like

I see. It makes sense. Thank you so very much for your guidance!!! Much appreciated!

1 Like

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