Returning infinite loop? Why? (in Symmetric Difference challenge)

Returning infinite loop? Why? (in Symmetric Difference challenge)
0

#1

Hi guys, can anyone help me figure out why this is returning an infinite loop? This is for the symmetric difference algorithm challenge. I just don’t understand what’s going on

``````function sym(args) {
var arr2 = [];
var hold = 0;
//split out argument into seperate arrays
args = Array.prototype.slice.call(arguments);

//reduce over loops that get symmetric difference between 2 arrays
args.reduce(function(prev, curr) {
//loop over array 1
for (let i = 0; i<prev.length; i++) {
//loop over array 2
for (let j = 0; j<curr.length; j++) {
//if array 1 item matches anything in array 2 then add value to hold (count tracker)
if (prev[i] === curr[j]) {

hold++;
}
}
//if hold is 0 then theres no matches so can be added
if(hold === 0) {
arr2.push(prev[i]);
}

hold = 0;

}

//now do same as above but checking array 2 against array 1
for (let i = 0; i<curr.length; i++) {

for (let j = 0; j<prev.length; j++) {
if (curr[i] === prev[j]) {
hold++;
}
}

if(hold === 0) {
arr2.push(curr[i]);
}

hold = 0;

}

return arr2;

});

return arr2;

}

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

#2

Array.prototype.reduce() reduces an array down to a single value, but the value that your reduce function is returning is an array.

#3

Not a direct answer to the question and I’m not familiar with the challenge, but I would suggest you try to decompose the problem.

At the moment you have something like 40 lines of code solving this problem and you know that there’s a problem in there somewhere.

What you ideally should have is something like the pseudo code below. Then you can change your question from “I don’t understand why there’s an infinite loop in my code” to “I don’t understand why there’s an infinite loop in my first function”. If the functions are small enough that’s a more manageable problem.

Hope that helps.

``````function sym(args) {
var returnValue = firstFunction(args);
var secondReturn = secondFunction(returnValue);
}

function firstFunction(args)
{
// does something
}

function secondFunction(args)
{
// does something else
}
``````

#4

Hi there @saf94, I believe your problem is when you test if hold is equal to zero. try commenting those two sections of code out and running it again.

As far as I can tell, when hold === 0, your if () statement gets looped, and the program just keeps pushing prev[i]/curr[i] to arr2.

I hope that is useful! Good luck!

#5