link to the challenge : https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/sorted-union
why my code is returning an empty array arr1 = [] ?
Here is my code :
function uniteUnique(arr) {
let arr1 = [];
for(let i = 0; i < arr.length; i++){
for(let j = 0; j < arr[i].length; j++){
if(arr1.indexOf(arr[i][j]) === -1){
arr1.push(arr[i][j]);
}
}
}
return arr1;
}
console.log(uniteUnique([1, 3, 2], [5, 2, 1, 4], [2, 1]));
-This looks like a challenge, can you link the challenge here.
Next Time if you need a help from a challenge, you can use the Get Help
button on the sidebar.
1 Like
It outputs 0, because over here:
for(let i = 0; i < arr.length; i++){
console.log(arr[i])
for(let j = 0; j < arr[i].length; j++){
console.log(arr[j])
if(arr1.indexOf(arr[i][j]) === -1){
arr1.push(arr[i][j]);
}
}
}
uniteUnique([1, 3, 2], [5, 2, 1, 4], [2, 1]);
You are saying that if i < arr.length
which is 3 from the console.log
, because the first argument only have 3 items. Then you are testing if j < arr[i].length
the length is 1 because arr[0]
is 1
and it is only a single number without length.
- The problem you are having is that you don’t have anyway to take all of the arguments, because you never know how many arguments is going to be passed through the parameter. You can solve this using the
[...arguments]
. This will grab all the argument from the parameter. Then you can loop through all of them and try to solve the challenge
oh. yeah how did i not notice that mistake ! thanks man i appreciate the help
1 Like