veron veron - 1 month ago 7
Javascript Question

Javascript - Find Symmetric Difference - Error with For Loop

Below is my solution to FreeCodeCamp's "Symmetric Difference" challenge.

The correct code should return 2, 3, 4, 6, 7. Why is my code returning 2, 3, 4, 6?

function sym(args) {
args = Array.from(arguments);
var newArr = [];

function removeFirstIndex() {
for (var i = 0; i <= args[1].length; i++) {
if (args[1].indexOf(args[0][i]) === -1) {
newArr.push(args[0][i]);
}
if (args[0].indexOf(args[1][i]) === -1) {
newArr.push(args[1][i]);
}
}
args = args.splice(2);
args.unshift(newArr);
newArr=[];
}
while (args.length>1){
removeFirstIndex();
}
args=args.reduce(function(a,b){
return a.concat(b);
});
args=args.filter(function(elem,pos,self){
return self.indexOf(elem)===pos && elem!==undefined;
});
return args.sort();
}
sym([3, 3, 3, 2, 5], [2, 1, 5, 7], [3, 4, 6, 6], [1, 2, 3]); // should return 2, 3, 4, 6, 7

Answer

Your inner for loop runs i to the length of one of the two arrays, yet you use that index to address an element in both arrays. If they are not the same length you will either skip elements, or check values beyond the length of the shorter array.

So you need to split that loop into two separate loops:

    for (var i = 0; i <= args[0].length; i++) {
        if (args[1].indexOf(args[0][i]) === -1) {
            newArr.push(args[0][i]);
        }
    }
    for (var i = 0; i <= args[1].length; i++) {
        if (args[0].indexOf(args[1][i]) === -1) {
            newArr.push(args[1][i]);
        }
    }

This fixes your issue.

Now, you could improve on this, by using hashing, which you can do with a Set.