I am trying to understand how array.filter is returning array differences by checking if indexOf(x) is equal to -1? Why -1?
function array_diff(a, b) {
return a.filter(function(x) { return b.indexOf(x) == -1; });
}
I am trying to understand how array.filter is returning array differences by checking if indexOf(x) is equal to -1? Why -1?
function array_diff(a, b) {
return a.filter(function(x) { return b.indexOf(x) == -1; });
}
indexOf(x) return the index of your property. So 0 is the first property, -1 means there is no property found.
b.indexOf(x)
returns the index of parameter x
in array b
, or -1
if x
is not found in array b
.
So, if x
doesn't exist in both the a
and b
array, indexOf()
returns -1
, allowing x
to appear in the result.
function array_diff(a, b) {
return a.filter(function(x) { return b.indexOf(x) == -1; });
}
For each item of array a
, see if it exists in array b
. If it does not (indexOf()
returns -1
), so return true, and keep it in the array. If it is in both arrays, return false.