Skip to content

Instantly share code, notes, and snippets.

@athoug
Last active January 7, 2020 23:34
Show Gist options
  • Save athoug/ba223970bc694262aefd38526a1c1056 to your computer and use it in GitHub Desktop.
Save athoug/ba223970bc694262aefd38526a1c1056 to your computer and use it in GitHub Desktop.
The goal is to implement a difference function, which subtracts one list from another.
function array_diff(a, b) {
// This here is the wwrong approach where the length keeps decresing so
// the map function wouldn't check all the arrays element
a.map(function(element){
for(var i =0; i <b.length; i++){
if(element === b[i]){
a.splice(a.indexOf(element),1);
break;
}
}});
return a;
}
// a better approach where you filter the array
// and the condition is that the element in a
// returns a -1 in array b meaning it doesnt exist there
function array_diff(a, b) {
return a.filter(function(x) { return b.indexOf(x) == -1; });
}
@athoug
Copy link
Author

athoug commented Jul 3, 2016

Thank you @ReemAlJunaid it worked! Thanks also for pointing out the length property change. it didn't cross my mind so I thank you for that. With more research, I found a better solution a one liner check it out, I think it's pretty cleaver
function array_diff(a, b) { return a.filter(function(x) { return b.indexOf(x) == -1; }); }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment