Last active
January 7, 2020 23:34
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; }); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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; }); }