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

I however keep getting an error. [more like the wrong output] when testing it with this example
array_diff([1,2,2], [2]);

I keep getting a [1,2] when i should be getting a [1]
can someone tell me what I'm doing wrong?

@ReemAlJunaid
Copy link

ReemAlJunaid commented Jul 3, 2016

document.writeln (array_diff([1,2,4,5,2], [2]));
function array_diff(a, b) {
a.map(function(element){
for(var i =0; i <b.length; i++){
if(element === b[i]){
a[a.indexOf(element)]=null;
break;
}
}});
a = a.filter(function(n){ return n !=null });

return a;
}

You should replace it with null or any special character, then remove all these special characters before returning the array.

@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