freeCodeCamp Algorithm Challenge Guide: Diff Two Arrays

freeCodeCamp Algorithm Challenge Guide: Diff Two Arrays
0.0 0

#1

:triangular_flag_on_post: Remember to use Read-Search-Ask if you get stuck. Try to pair program :busts_in_silhouette: and write your own code :pencil:

:checkered_flag: 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

:speech_balloon: Hint: 1

Merge the list to make it easy to compare functions.

try to solve the problem now

:speech_balloon: Hint: 2

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

try to solve the problem now

:speech_balloon: 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.

try to solve the problem now

Spoiler Alert!

687474703a2f2f7777772e796f75726472756d2e636f6d2f796f75726472756d2f696d616765732f323030372f31302f31302f7265645f7761726e696e675f7369676e5f322e676966.gif

Solution ahead!

:beginner: Basic Code Solution (Imperative Solution):

function diffArray(arr1, arr2) {
  var newArr = [];
  
  function onlyInFirst(first, second) {
  // Looping through an array to find elements that don't exist in another array
    for (var 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]);

Run Code :rocket:

Code Explanation:

Read the comments in the code.

Relevant Links

:sunflower: Intermediate Code Solution (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]);

Run Code :rocket:

Code Explanation:

Explain solution here and add any relevant links

Relevant Links

:rotating_light: Advanced Code Solution (Declarative Solution):

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

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

Run Code :rocket:

Code Explanation:

Explain solution here and add any relevant links

Relevant Links

:clipboard: NOTES FOR CONTRIBUTIONS:

  • :warning: DO NOT add solutions that are similar to any existing solutions. If you think it is similar but better, then try to merge (or replace) the existing similar solution.
  • Add an explanation of your solution.
  • Categorize the solution in one of the following categories – Basic, Intermediate and Advanced. :traffic_light:
  • Please add your username only if you have added any relevant main contents. (:warning: DO NOT remove any existing usernames)

See :point_right: Wiki Challenge Solution Template for reference.


A Better Solution? - Diff Two Arrays
#2

#3

#4

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;
}

#5

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


#6

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]


#7

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);
}

#8

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


#9

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


#10

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]);

#11

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;
}


#12

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]);


#13

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 ;


#14
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.


#15

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]);


#16

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.


#17

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]);

#18

@Albano-J - I liked your solution and decided to make it into a more functional version:

function diffArray(arr1, arr2) {
  return arr1.concat(arr2).filter((elem,_,arr) => arr.lastIndexOf(elem)==arr.indexOf(elem));
}

but after some extra testing (beyond FCC tests), I found a situation where yours would fail (see below):

diffArray([1, 2, 3, 5], [1, 2, 3, 4, 4,5]); // should return [4,4] but instead returns []

If there are duplicates of an element which are in on array and not the other, then it will not include them even when it should. Again, yours does pass the FCC tests, which is why I liked it so much and made the functional version. The FCC tests assume there would be no duplicates in either array.


#19

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!


#20
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;
}