freeCodeCamp Challenge Guide: Diff Two Arrays

this works assuming that both arrays have only unique elements (no 2 identical elements in one array), which is true in this exercise, but in real life may not be (or at least you may not be sure if a unique dataset will be thrown at the algorithm).

2 Likes

That’s ES6 - a new way of writing the JS code. I agree, it’s confusing and makes learning a bit harder, but because these examples are written by volunteers and not the original creators of this course we will continue seeing this mixture of ES5 and ES6. The only thing you can do is google up “JavaScript ES6” (or “JavaScript ECMAScript 2015” - the same thing) and spend an hour or two reading about it. It will make things much clearer.

1 Like

Thank you so much. I will try to fix my code, but now I’m a bit confused: what is the expected result for diffArray([1, 2, 2], [1, 2]);? Because all the given solutions return an empty array, but I think that it should be [2].

in this case an empty array is the correct answer as none of these arrays have a unique number the other one wouldn’t have.

This is my solution:

function diffArray(arr1, arr2) {
  var newArr = [];
  var diff1, diff2;
  
  if(arr1.length < 1){
    newArr = arr2;
  }
  if(arr2.length < 1){
    newArr = arr1;
  }
  
  diff1 = arr2.filter(function(i){
    return arr1.indexOf(i) < 0;
  });
  diff2 = arr1.filter(function(i){
    return arr2.indexOf(i) < 0;
  });
  
  return diff1.concat(diff2);
}

//test
diffArray([], ["snuffleupagus", "cookie monster", "elmo"]);

My solution: concat, sort, compare:

function diffArray(arr1, arr2) {
  var newArr = (arr1.concat(arr2)).sort();
  return newArr.filter(function(currentValue, i, arr){
      return  (i===0 || arr[i]!=arr[i-1]) && (arr.length==i+1 || arr[i]!=arr[i+1]);                  
    });
}

Spent huge time & didn’t find a solution.

6 Likes

My solution with concat, filter and indexOf:

function diffArray(arr1, arr2) {

  var newArr = arr1.concat(arr2);

  var diffValues = newArr.filter(function(val){
    if (arr1.indexOf(val) < 0 || arr2.indexOf(val) < 0) {
      return val;
    } 
  });

  return diffValues;
}

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

Seems to work. Not sure that I understand the other solutions.

3 Likes

It seems like I’m the only one who used splice:

function diffArray(arr1, arr2) {
  var newArr = [];
  
  // destroy matches in both arrays
  for (var i=0; i<arr1.length; i++){
    for (var j=0; j<arr2.length; j++){
      if (arr2[j] === arr1[i]) {
        arr2.splice(j,1);
        arr1.splice(i,1);
        j--;
      }
    }
  }
  
  newArr = arr1.concat(arr2);
   
  return newArr;
}

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

This is the solution i came up with, a little bit cumbersome, i know. :stuck_out_tongue:

function diffArray(arr1, arr2) {
    var newArr = [];
    var dummy;
    var dummy2;
    var maxSize;
    // Same, same; but different.
    if (arr1.length >= arr2.length) {
        maxSize = arr1.length;
    } else {
        maxSize = arr2.length;
    }

    for (let i = 0; i < maxSize; i++) {
        dummy = arr1.indexOf(arr2[i]);
        dummy2 = arr2.indexOf(arr1[i]);

        if (dummy2 === -1 && arr1[i] !== undefined) {
            newArr.push(arr1[i]);
        }
        if (dummy === -1 && arr2[i] !== undefined) {
            newArr.push(arr2[i]);
        }
    }

    console.log(newArr);
    return newArr;
}

I acutally worked out three solutions because I tried to improve myself each time:

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

diffArray([1, "calf", 3, "piglet"], [1, "calf", 3, 4]);


// Solution 2
function diffArray(arr1, arr2) {
    var newArr = [];
    // Same, same; but different.
    var filteredArr = arr1.concat(arr2).filter(function(elem) {
        
        if(arr1.indexOf(elem) == -1) {
            newArr.push(elem);
        }
        
        if(arr2.indexOf(elem) == -1) {
            newArr.push(elem);
        }
    });
    
    return newArr;
}

diffArray([1, "calf", 3, "piglet"], [1, "calf", 3, 4]);


 // Solution 3
function diffArray(arr1, arr2) {
    return arr1.concat(arr2).filter(function(elem) {
        return arr1.indexOf(elem) == -1 || arr2.indexOf(elem) == -1; 
    });
}

diffArray([1, "calf", 3, "piglet"], [1, "calf", 3, 4]);


// shorthand for Solution 3
function diffArray(arr1, arr2) {
    return arr1.concat(arr2).filter(elem => arr1.indexOf(elem) == -1 || arr2.indexOf(elem) == -1);
}

diffArray([1, "calf", 3, "piglet"], [1, "calf", 3, 4]);
1 Like

Here is mine.

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

  for (var i = 0; i < arr1.length; i++) {
    if(arr2.indexOf(arr1[i]) < 0){
      newArr.push(arr1[i]);
    }
  }
  for (var j = 0; j < arr2.length; j++) {
    if(arr1.indexOf(arr2[j]) < 0){
      newArr.push(arr2[j]);
    }
  }
    return newArr;
}
4 Likes

I came up with this solution, but i’m not sure if the use of delete is considered “best practice”, but it works.

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

// Loop trough arr2
for(var i = 0; i < arr2.length;i++)
{
// if this Condition doesn’t return -1 delete the element in arr1 at this position
if(arr1.indexOf(arr2[i]) !== -1)
{
delete arr1[arr1.indexOf(arr2[i])];
}// if it does return -1 push the element in the new array
else
newArr.push(arr2[i]);
}
// At the end concat newArr and arr1, the filter at the end is just to get rid of null entries in the array
// even tough the Test run well also without the filter
return newArr.concat(arr1).filter(function(val){
if(val)
return val;
});
}

Solution 1

function diffArray(arr1, arr2) {
  var result = [];
  `// loop through arr1 elements`
  for (i = 0; i < arr1.length; i++) {
   `// if an element of arr1 is not present in arr2`
    if (arr2.indexOf(arr1[i]) === -1) {
      `// push that element in result`
      result.push(arr1[i]);
    }
  }
  `// loop through arr2 elements`
  for (i = 0; i < arr2.length; i++) {
   `// if an element of arr2 is not present in arr1`
    if (arr1.indexOf(arr2[i]) === -1) {
      `// push that element in result`
      result.push(arr2[i]);
    }
  }
  return result;
}

Solution 2 (works with more then two arrays)

function diffArray(arrays) {
  var count = [];
  var result = [];
  // merge all arrays passed as argument
  var arr = [].concat.apply([], arguments);

  // select an element (e1)
  arr.forEach(function(e1) {
    // count how many times e1 is inside the array
    count = arr.filter(function(e2){
      return e1 === e2;
    });
    // if e1 only found one times
    if (count.length === 1) {
      result.push(e1);
    }
  });

  return result;
}
3 Likes

Sleep helps… I spent over an hour working on it last night…was so stuck…fell asleep on it (literally) then woke up, got a cup of coffee, and solved it in 10 minutes. Eeep! Though to be fair, a lot of the time last night was spent thinking how I’m going to solve it, then what I was trying to do with my tired brain finally was clear to me this morning.

Anyway, been looking at other solutions and don’t see others quite like mine, so wanted to share it. Certain it could be done in a more concise way… I’m just proud of myself for coming up with a solution with no hints. Eeep!

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

//combine the two arrays
  var oneArr = arr1.concat(arr2);

//sort the array
  if (typeof oneArr[1] === 'string') {
  	oneArr.sort();
  } else {
  oneArr.sort(function(a,b) {return a-b;});
  }
  
//iterate through array
//if value is not equal to what comes before or after it, add to newArr
  for (i = 0; i < oneArr.length; i++) {

    if (oneArr[i] !== oneArr [i + 1] && oneArr[i] !== oneArr[i - 1]) {
    	console.log("Remaining: " + oneArr[i]);
    	newArr = newArr.concat(oneArr[i]);
    } 
  }
  console.log(newArr);
  return newArr;
}

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

my solution

function diffArray(arr1, arr2) {
  var newArr = arr1.concat(arr2);
  newArr = newArr.filter(function (val) {
    return arr1.indexOf(val) < 0 || arr2.indexOf(val) < 0;
  });
  // Same, same; but different.
  return newArr;
}

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

I wrote the exact way with the only difference is that I used include() instead of indexOf.

if ( !arr1.includes(joinedArr[i]) || !arr2.includes(joinedArr[i]) ){

3 Likes

I created two filters and concatenated them, as much for (human) readability as anything else

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

  var filter1 = arr1.filter(function(item) {
    return arr2.indexOf(item) < 0;
  });
  
  var filter2 =  arr2.filter(function(item) {
    return arr1.indexOf(item) < 0;
  });
 
  newArr = filter1.concat(filter2);
  return newArr;
}
1 Like

Hi @sgenio

This is my simple solution

function diffArray(a, b){
 c = a.concat(b)
 d = [];
var diffarr = c.filter(function(c1){
	   if (a.indexOf(c1) === -1 || b.indexOf(c1) === -1){
	   		d.push(c1);
	   }
	});
	return d;
}
diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]);

Hi Friends

This is my solution

function diffArray(a, b){
 c = a.concat(b)
 d = [];
var diffarr = c.filter(function(c1){
	   if (a.indexOf(c1) === -1 || b.indexOf(c1) === -1){
	   		d.push(c1)
	   }
	})
	return d
}
diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]);