freeCodeCamp Challenge Guide: Diff Two Arrays

Diff Two Arrays


Problem Explanation

Check two arrays and return a new array that contains only the items that are not in either of the original arrays.

Relevant Links


Hints

Hint 1

Merge the list to make it easy to compare functions.

Hint 2

Use filter to get the new array, you will need to create a callback function.

Hint 3

The best way to go about the callback function is to check if the number from the new merged array is not in both original arrays and return it.


Solutions

Solution 1 (Click to Show/Hide)

(Imperative Solution)

function diffArray(arr1, arr2) {
  const newArr = [];

  function onlyInFirst(first, second) {
    // Looping through an array to find elements that don't exist in another array
    for (let i = 0; i < first.length; i++) {
      if (second.indexOf(first[i]) === -1) {
        // Pushing the elements unique to first to newArr
        newArr.push(first[i]);
      }
    }
  }

  onlyInFirst(arr1, arr2);
  onlyInFirst(arr2, arr1);

  return newArr;
}

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

Code Explanation

Read the comments in the code.

Relevant Links

Solution 2 (Click to Show/Hide)

(Declarative Solution):

function diffArray(arr1, arr2) {
  return arr1
    .concat(arr2)
    .filter(item => !arr1.includes(item) || !arr2.includes(item));
}

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

Code Explanation

Explain solution here and add any relevant links

Relevant Links

Solution 3 (Click to Show/Hide)

(Declarative Solution)

function diffArray(arr1, arr2) {
  return [...diff(arr1, arr2), ...diff(arr2, arr1)];

  function diff(a, b) {
    return a.filter(item => b.indexOf(item) === -1);
  }
}

Relevant Links

Solution 4 (Click to Show/Hide)

(Declarative Solution)

function diffArray(arr1, arr2) {
  const difference = new Set(arr1);
  arr2.forEach((ele) =>
    difference.has(ele) ? difference.delete(ele) : difference.add(ele)
  );
  return Array.from(difference);
}

Relevant Links

129 Likes

I don’t know if this is a suitable solution since I’m still a newbie, but it works, without using indexOf and filter methods. I do not know if it is a basic, intermediate or advanced solution.

687474703a2f2f7777772e796f75726472756d2e636f6d2f796f75726472756d2f696d616765732f323030372f31302f31302f7265645f7761726e696e675f7369676e5f322e676966.gif

function diffArray(arr1, arr2) {
   var newArr = []; 

//concatenate the two arrays and sort the items in growing order
   var ordArr = arr1.concat(arr2).sort(); 

//loop through the ordered array and push to the empty newArr only the items that have not a twin in the ordered arr (only items that are not equal to the previous nor to the next item)
   for(var i=0; i<ordArr.length; i++) {
       if(ordArr[i] !== ordArr[i+1] && ordArr[i] !== ordArr[i-1]){
       newArr.push(ordArr[i]);
       }
   }

   return newArr;
}
52 Likes

I just kept thinking ahead, instead of behind as well. I like yours best! Simple rationality !!!

1 Like

function diffArray(arr1, arr2) {

var newArr = [];

// Sort Array 1
arr1.sort(function (a,b){
return a.length-b.length;
});

// Sort Array 2
arr2.sort(function (a,b){
return a.length-b.length;
});

for (var i = 0; i<arr1.length; i++){

for(var j = 0; j<arr2.length; j++){
  
  if(arr1[i] === arr2[j]){
    
    delete arr1[i];                       // remove common elements from arr1 and arr2
    delete arr2[j];
  }
}

}
newArr = (arr1.filter(Boolean)).concat(arr2.filter(Boolean)); // concat the two arrays after removing the Boolean values like null, undefined which may have been there after deleting the array elements
return newArr;
}

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

Output: [4]

8 Likes

My solution:

function diffArray(arr1, arr2) {
  // filter each array for the absent members
  var filteredArr1 = arr1.filter((el) => arr2.indexOf(el) === -1),
      filteredArr2 = arr2.filter((el) => arr1.indexOf(el) === -1);

  // merge both sets of absent members
  return filteredArr1.concat(filteredArr2);
}
54 Likes

Hi I really like your solution, especially that it is much shorter than mine. But I see syntax like .filter((el) => arr…)
And I dont mean filter method, but => statement. What is it? How to call it and where can I find any tutorial about it?

Thanks in advance.
Kamil

2 Likes

=> is the es6 “fat arrow” function syntax.

4 Likes

Hi there, I have just completed diff two arrays bonfire. Comment on the solutions please and any suggestions for improvement are welcome. Thanks



function diffArray(arr1, arr2) {

  return arr1.filter(function(elem){
    return arr2.indexOf(elem) < 0;
  }).concat(arr2.filter(function(elem){
    return arr1.indexOf(elem) < 0;
  }));

 
}


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

I’m a complete newb, here was my attempt. (I’m addicted to for loops… :slight_smile: )

function diffArray(arr1, arr2) {
var arr3 = arr1.concat(arr2);

for (i=0; i < arr3.length; i++){
for (j=0; j< arr2.length; j++){
for (k=0; k<arr1.length; k++){
if (arr1[k] === arr3[i] && arr2[j] === arr3[i]){
delete arr3[i];
}
}
}
}
return arr3;
}

7 Likes

an other solution which is almost the same as belcurv one:

function diffArray(arr1, arr2) {
var newArr = [];
// Same, same; but different.
newArr = arr1.filter(val => { return arr2.indexOf(val) === -1; }).concat(arr2.filter(val => { return arr1.indexOf(val) === -1; }));
return newArr;
}

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

1 Like

Hi there , here’s my approach

var newArr = arr1.concat(arr2); //concat both arrays sorting
var singledout=[];
for (i=0;i<newArr.length;i++)
{
if (newArr.indexOf(newArr[i])==newArr.lastIndexOf(newArr[i]))
{
singledout.push(newArr[i]); //add item only if its once in the array
}
}

return singledout ;

1 Like
function diffArray(arr1, arr2) {
 return arr1 //returns the final iteration of the array
.concat(arr2) //combines arr1 and arr2 into a  new array
.filter( //creates a new array with elements that pass a test
item => //this is a shorthand for a function expression
!arr1.includes(item) //this is a test that only passes elements that are NOT included in arr1
|| !arr2.includes(item) //this is a test that only passes elements that are NOT included in arr2
   )
}

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

I found it tricky to understand how the intermediate solution actually worked and the elements involved in it. Therefore I broke down each step and tried to explain it in comments. This has helped me to understand the more complex code going on here. Could someone please let me know if any of my explanations are incorrect and if this is the right way to contribute.

9 Likes

I have also gone through the advanced code solution, adding comments. It seems that the only differences between the intermediate and advanced solutions are:

  1. that “item” has been replaced with “el” which suggests that these are labels that can be almost anything you like.
  2. The filtering of arr1 has happened before the concat element which means that filter has to be called twice and there is no need for an “or ||” call.
  3. It would appear that the advanced solution is a little less intuitive and demonstrates that ordering is not as fixed as it seems.

function diffArray(arr1, arr2) { return arr1 //returns the final iteration of the array .filter(el => !arr2.includes(el)) //filters out all elements from arr1 except those that are not in arr2 .concat( //combines filtered arr1 with the soon-to-be filtered arr2 arr2.filter(el => !arr1.includes(el)) //filters out all elements from arr2 except those that are not in arr1 ) } diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]);

2 Likes

Try looking to functional programming and higher order function. You will be amazed that how easier your life be with functional programming and loops will be in lower priority.

3 Likes

Hey guys, this is my solution. Any feedback about it is welcome.

function diffArray(arr1, arr2) {
  var newArr = [];
  // Same, same; but different.
  
  var newConcat = arr1.concat(arr2);
  
  for (var i = 0; i < newConcat.length; i++) {
    if (arr1.indexOf(newConcat[i]) === -1 || arr2.indexOf(newConcat[i]) === -1) {
     newArr.push(newConcat[i]);
    }
  }
  return newArr;
}

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

I’d like to see something besides the Basic Code Solution that doesn’t include whatever => is, since freeCodeCamp hasn’t taught => at this point. I’m trying to understand just how .filter works, so a solution that included something like that, but didn’t include things that freeCodeCamp hasn’t covered at all yet so that it would be possible to do it without going outside the bounds of what an actual beginner learning from freeCodeCamp could do, would be helpful.

Anyway, thank you for putting this up!

4 Likes
function diffArray(arr1, arr2) {
  var newArr = arr1.concat(arr2);
  // Same, same; but different.
  newArr=newArr.filter(function(el){
    if(arr1.indexOf(el)>-1){
      if(arr2.indexOf(el)>-1){
        console.log(el+"Present in Both");
        return false;
      }
      else{
        return true;
      }
    }
    if(arr2.indexOf(el)>-1){
      if(arr1.indexOf(el)>-1){
        console.log(el+"Present in Both");
        return false;        
      }
      else{
        return true;
      }
    }
  });
  return newArr;
}
2 Likes

This is the solution I found. Any tip to improve the code?

function diffArray(arr1, arr2) {
var newArr = [];

for(var j = 0; j < arr1.length; j++) {
collectInexistent(arr2, arr1[j], newArr);
}

for(var i = 0; i < arr2.length; i++) {
collectInexistent(arr1, arr2[i], newArr);
}

// Same, same; but different.
return newArr;
}

function collectInexistent(arr, element, newArr) {
if(arr.indexOf(element) === -1) {
if(!!element)
newArr.push(element);
}
}

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