Currently, I'm tackling a challenge that involves the array_diff
function, which aims to retrieve values from array a
that also exist in array b
.
Having recently learned about the advantages of named function expressions for console debugging over anonymous fat arrow functions, I decided to approach this problem by creating a named function called removeDuplicate
to filter my array.
Despite my efforts, I've encountered an issue where the filter function unintentionally eliminates the falsey value 0 from the output array.
This is the structure of the named function expression:
function array_diff(a, b) {
return a.filter(function removeDuplicate(x) { if(b.indexOf(x) == -1) return x; });
}
array_diff([0,1,2,3,4],[2,4]); // [1, 3]
And here is the same logic implemented using an Anonymous Fat Arrow function:
function array_diffTwo(a, b) {
return a.filter((x) => { return b.indexOf(x) == -1 });
}
array_diffTwo([0,1,2,3,4],[2,4]); // [0, 1, 3]
I'm seeking clarification on why the falsey value 0 gets removed in array_diff
but not in array_diffTwo
. Any insights would be greatly appreciated!