Diff Two Arrays - Help please

Tell us what’s happening:
I’m not sure what’s wrong. I get some of the challenges to pass but not others with similar problems. I removed the global variables and used if else to run through test options. For some reason the result.push(); is not logging all !== array elements.

Any help would be appreciated.

Your code so far




function dedupe (arr) {
  let result = [];
  // base case
  if ( arr === [] ) {
    //console.log(result);
    return result; 
  }else if ( arr.length === 1 ) {
    result.push(arr[0]);
    //console.log(result);
    return result; 
  }else if ( arr.length === 2 && arr[0] !== arr[1] ) {
    result.push(arr[0]);
    result.push(arr[1]);
    //console.log(result);
    return result; 
  }else if ( arr.length === 2 && arr[0] === arr[1] ) {
    //console.log(result);
    return result; 
  }else if ( arr.length > 2 && arr[0] === arr[1] ) {
    console.log(result);
    return dedupe(arr.slice(2)); 
  }else if( arr.length > 2 && arr[0] !== arr[1] ) {
    result.push(arr[0]);
    console.log(result);
    return dedupe(arr.slice(1));
  }
      
}

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

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

Your browser information:

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

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/diff-two-arrays

I did not completely debug your code but with a quick glance I noticed two parts that can cause unexpected results:

  1. You are using recursion (I love that you are experimenting with this). However this means that you keep initiating the function “dedupe”. The first thing you do in dedupe, is define your result array… Do you see the problem with this? You are actually resetting your result over and over again.

  2. Your sort fuction could be causing unexpected results.

For example the following test:

[1, “calf”, 3, “piglet”], [1, “calf”, 3, 4] should return [“piglet”, 4].

Currently (after fixing the problem discussed in point 1), your function returns: [4, “piglet”]. I don’t know if FCC tests will allow this or not, but it could be causing problems.

Finally I wanted to comment that when you are looking for items in an array, using the function indexOf(), is usually a good idea ;). However the infinite possibilities of solving problems is what makes writing code so fun, so keep doing what you are doing but just keep it in mind for future challenges :smiley: