Diff of Arrays -- I would like to know a better way to solve it

Diff of Arrays -- I would like to know a better way to solve it
0

#1

I know their is no official way to solve a problem, but i’d love to see yours. My way solves the tests, but I feel like it could be more clever.


function diffArray(arr1, arr2) {

newArr =[];
newArr2=[];

//gets comparisons for arr1 
for(i=0; i < arr1.length; i++){

	
	if(arr2.indexOf(arr1[i]) == -1 ){
		newArr.push(arr1[i]);
	}
	newArr
}

// gets comparisons for arr2

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

	if(arr1.indexOf(arr2[i]) == -1 ){
		newArr2.push(arr2[i]);
	}
	newArr2
}


var x = newArr.concat(newArr2);

return x;

}

#2

I concat the 2 arrays and using an object, I count the number of times each number is present in the array.I filter the array to keep elements that appear just once :

const sym = function() {

	Array.prototype.unique = function() {
	  return this.filter((el, index, arr) => index === arr.indexOf(el)); // [1,1,2,3].unique() === [1,2,3]
	};

	Array.prototype.occurences = function() {
		return this.reduce( (counts, item) => {
			counts[item] = !counts.hasOwnProperty(item) ? 1 : counts[item] + 1 ;
			return counts;
		}, {});
	}

	function symmetricDifference(arr1, arr2) {
	  	const arr = [...arr1.unique(), ...arr2.unique()];
	  	const occurencesOf = arr.occurences();
	  	return arr.filter(element => occurencesOf[element] === 1);
	}
  
	return [].slice.call(arguments).reduce(symmetricDifference);
}