# Diff Two Arrays - with Recursion?

Tell us what’s happening:

Not sure why the code below doesn’t work. I’ve run through the test cases in JSBin successfully here (http://jsbin.com/bokifaceku/edit?js,console), but running in FCC still doesn’t pass. Halps?

``````
var result = [];

function dedupe (arr) {

// base case
if ( arr === [] ) {
return result;
}

if ( arr.length === 1 ) {
result.push( arr[0] );
return result;
}

if ( arr.length === 2 && arr[0] !== arr[1] ) {
arr.map ( elt => result.push(elt) ).sort();
return result;
}

if ( arr.length === 2 && arr[0] === arr[1] ) {
return result;
}

// recursive case
let a = arr.sort();
if ( a[0] === a[1] ) {
return dedupe (a.slice(2));
} else {
result.push(a[0]);
return dedupe (a.slice(1));
}

}

function diffArray(arr1, arr2) {
return dedupe(arr1.concat(arr2));
}

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

User Agent is: `Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36`.

Your algorithm looks great and works perfectly. It should work on FCC. I’m having a similar issue with another challenge right now, where it works in codepen, but not fcc… sorry I can’t help more than to say, you’re not alone

PS: when this happens, I just keep writing variations of my solution, until it’s accepted by FCC’s tests, keeping track of my various solutions on a separate document as I go.

Your code contains global variables that are changed each time the function is run. This means that after each test completes, subsequent tests start with the previous value. To fix this, make sure your function doesn’t change any global variables, and declare/assign variables within the function if they need to be changed.

Example:

``````var myGlobal = [1];
function returnGlobal(arg) {
myGlobal.push(arg);
return myGlobal;
} // unreliable - array gets longer each time the function is run

function returnLocal(arg) {
var myLocal = [1];
myLocal.push(arg);
return myLocal;
} // reliable - always returns an array of length 2
``````
1 Like

@ArielLeslie got one great point, very good!

I was thinking, for each run FCC may uses one new context, but seems it’s shared.

Just reset the global var `result` for each call in your diff func, as following

``````function diffArray(arr1, arr2) {
result=[];
return dedupe(arr1.concat(arr2));
}
``````

Keep goin on great work, happy programming

Looks like emptying the result array each time diffArray is run worked:

function diffArray(arr1, arr2) {
if ( result !== [] ) {
result = [];
}
return dedupe(arr1.concat(arr2));
}