Hey, so I can’t figure out the problem because the code is confusing, but even without the error it would fail. So I’d like to help you fix the whole thing from scratch.
So there are a few issues with your code. For starters, remove the console.logs, they don’t contribute anything to your code.
Second, arr only refers to the first array, that is arguments[0], so your first for loop is pointless because it is basically pushing only elements of the first array(in this case [1, 2, 3]) to arr2, meaning arr2 is [1, 2, 3]. Also, push is the wrong syntax, concat is the best one : https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/concat
If you want to put all elements into one array, then this is the right way
for(var i= 0; I < arguments.length; I++) {
arr2 = arr2.concat(arguments[i]);
}
this code loops through arguments(where arguments[0] is arr), and merges all every arguments[I] with arr2. So now your arr2 will be [1, 2, 3, 5, 2, 1].
Now after merging all arrays into arr2, you can create a new empty array to hold the unique elements
var unique = [];
and now you can loop through arr2 and push only unique elements into unique
for(var j = 0. j < arr2.length; j++) {
if(unique.indexOf(arr2[j]) < 0) {
unique.push(arr2[j]);
}
}
this code checks an element at position j in arr2 exists in unique, if it does not, then it is added to unique, so in our case 1, 2, 3 and 5 will be added to unique.
alternatively you can use reduce https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce
unique = arr2.reduce(function(a, b) {
if(a.indexOf(b) < 0) {
a.push(b);
}
return a;
}, []);
in this case, a is the empty array here: }, []);
and b is the element in arr2. So it loops through arr2 and if the element is not in the empty array(a) it pushes it to a.
return unique;
This code will work;
I hope this helps. I know I’ve shown you the whole answer, but don’t feel guilty about using it. There are times I’ve learned how to solve the next algorithm by studying someone else’s answer.
Also, learn to comment on your code, it gives people an easier idea of what your code does.
Good luck.