# Need help to understand my function behavior (Challenge : Sorted Union)

Hi, I’m trying to solve Sorted Union challenge. So, I come up with a function I expect to work but it doesn’t .
however when I tried a similar code in the console line by line (not in the form of function ) it works. So, I’m looking for explanation of why my function behave differently. I know there are better ways of solving the challenge, but for know I want to understand why my function behave as its . please help

``````function uniteUnique(arr) {
function flatten(arr) {
return [].concat(...arr)
}

const newArr = flatten(arr);
let sortedArr = [];

for (let i = 0; i < newArr.length; i++) {
if (newArr.indexOf(newArr[i]) === i) {
sortedArr.push(newArr[i]);
}
}
return sortedArr;
}

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

// <- Array [1,3];
``````

but when I test my code line by line (not in the form of function) it seems to work.

``````let arr = [[1, 3, 2], [5, 2, 1, 4], [2, 1]];
//<- undefined
function flatten(arr) {
return [].concat(...arr)}

const newArr = flatten(arr);
let sortedArr = [];
//<- undefined

for (let i = 0; i < newArr.length; i++) {
if (newArr.indexOf(newArr[i]) === i) {
sortedArr.push(newArr[i]);
}
}
// <- 5

sortedArr;
// <- Array(5) [ 1, 3, 2, 5, 4 ]

``````

In the first case, when you are passing the argument for the uniteUnique function, you forgot to put the outside brackets of the array.

the call back of uniteUnique function is part of Freecodecamp template of this challenge, is used to test the answer code provided by camper . I don’t think it’s a good idea to change it. any other reason perhaps?

Yeah, arr parameter points to the first argument, so [1, 3, 2] in your case. To work with other arguments you’d have to use the arguments object, I think.

1 Like

Thanks I got it