Skip to content

Instantly share code, notes, and snippets.

@P1xt
Last active November 21, 2015 05:07
Show Gist options
  • Save P1xt/6dbc91fc58c3f9ed729d to your computer and use it in GitHub Desktop.
Save P1xt/6dbc91fc58c3f9ed729d to your computer and use it in GitHub Desktop.
Javascript function to return an array containing the items that occur in one but not both input arrays. Need to refactor this.
/**
* diff two arrays - return the elements that occur in one but not both input arrays
* note to self: This works but there has to be a better (more performant) solution
* Revisit this and look into removing items from both arrays as they're discovered
**/
function diff(arr1, arr2) {
// get the items from arr1 that aren't in arr2
var filteredArr1 = arr1.filter( function( el ) {
return arr2.indexOf( el ) < 0;
} );
// now get the items from arr2 that aren't in arr1
var filteredArr2 = arr2.filter( function( el ) {
return arr1.indexOf( el ) < 0;
} );
// group them up and return them
return filteredArr1.concat(filteredArr2);
}
diff([1, 2, 3, 5], [1, 2, 3, 4, 5]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment