Diff Two Arrays please help :)

Tell us what’s happening:

Hello I was hoping someone would be kind enough give me some pointers.
I know there are many better ways write the code for this challenge, I believe my code is close to passing. I would like to complete the challenge without changing my code significantly if possible.

Your code so far


function diffArray(arr1, arr2) {
  var newArr = [];
  var box1 = arr1.sort(function (a,b) {
    return a > b;
  });
  var box2 = arr2.sort(function (a, b) {
    return a > b;
  });
  var ruler = box1.length + (box2.length - box1.length);
  for (var i = 0; i < ruler; i++) {
      if (box1.indexOf(box2[i]) < 0 && box2.indexOf(box1[i] < 0)) {
        newArr.push(box2[i]);
    }
  }
  console.log(newArr);
  return newArr;
}

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/69.0.3497.100 Safari/537.36.

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

A couple of thoughts:

1 - ruler: what’s the reason behind it? Is it to know the “shortest” array and so avoid excessive looping?

2 - your push condition always assume that the missing piece is in the second array, what if the missing is in box1?

Hope it helps :smile:

Thank you :slight_smile: everything helps. And yes that was the reason for ruler.

You are on the right track with indexOf. I don’t think sort is absolutely necessary though.

I think just start with an empty array called newArr

  1. Loop first array and check to see if element is in second array. If not push into newArr

  2. Loop second array and check to see if element is in first array. If not push into newArr

There may be slicker ways to do this but this solution can be done with two forEach or two for loops.

Thank you :slight_smile: It’s really helpful to hear different perspectives.

There are some pretty cool solutions if you click the hint button. My suggestion is essentially the same idea as the basic solution.

Recently I have been working on some of the interview prep algorithms and some of them are crazy hard. I like to give myself 30-60 minutes to work on it then I study the hints even if I get it right. It think its pretty cool to check out different ways of solving the same problem. Best of luck.

Here is a cool solution with similar concept to intermediate, i will blur it out.

function diffArray(arr1, arr2) {
  return [...arr1,...arr2].filter(el => {
    if(!(arr1.includes(el) && arr2.includes(el))) {
      return el
    } 
  })
}