# Find the Symmetric Difference. Need some help!

Find the Symmetric Difference. Need some help!
0

#1

Tell us what’s happening:

Having trouble with last 2 numbers in the 3rd array… For some reason I think it’s pushing 5 into nextArr variable but it’s getting spliced again.

I am failing this test case

sym([1, 1, 2, 5], [2, 2, 3, 5], [3, 4, 5, 5]) should return [1, 4, 5].

function sym() {
let newArr = [];
let nextArr = [];
let arr = Array.from(arguments);

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

for(let j=0; j<arr[1].length; j++) {
if(arr[0].indexOf(arr[1][j]) < 0 && newArr.indexOf(arr[1][j]) < 0) newArr.push(arr[1][j]);
}
for(let i=2; i<arr.length; i++) {
for(let j=0; j<arr[i].length; j++){
if(newArr.indexOf(arr[i][j]) < 0 && nextArr.indexOf(arr[i][j]) < 0)
nextArr.push(arr[i][j]);
else{
console.log("index " + nextArr.indexOf(arr[i][j]) + " val " + arr[i][j])
if(newArr.indexOf(arr[i][j]) >= 0) {
newArr.splice(newArr.indexOf(arr[i][j]), 1);
}
else{
nextArr.splice(nextArr.indexOf(arr[i][j]), 1)
}
}
console.log("j is " + j + " newArr " + newArr)
}
}
console.log("newArr " + newArr)
console.log("nextArr " + nextArr)
return newArr.concat(nextArr).sort((a,b) => a-b);
}

sym([1, 1, 2, 5], [2, 2, 3, 5], [3, 4, 5, 5])

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36.

#3

I had to go and solve it before I could respond again because the first time I misunderstood your logic. What I realized from solving this is that the algorithm is very important. In my case I used exactly 2 reduce statements. One to clean up each individual sub-array (removing duplicates from it) and then a 2nd reduce to identify and handle the duplicates between the arrays.

In your case above, I would suggest putting more logs into your code around the splice statements (printing exactly the current state of newArr and nextArray before and after the splice) so you can see where the flaw in the logic is.
(But here’s a clue: I hit the same issue until I decided to clean up each individual array of duplicates within them first).

#4

Thanks, let me work on that.