-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; });
}
Cerbrus
  • 70,800
  • 18
  • 132
  • 147
Felice
  • 571
  • 1
  • 7
  • 22

3 Answers3

0

indexOf(x) return the index of your property. So 0 is the first property, -1 means there is no property found.

Thibault Henry
  • 816
  • 6
  • 16
0

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.

Cerbrus
  • 70,800
  • 18
  • 132
  • 147
  • Thank you. This explanation makes most sense to me. I'm having a hard time really understanding the formula. – Felice Feb 18 '15 at 20:05
0
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.

Scimonster
  • 32,893
  • 9
  • 77
  • 89