var a = [7,8,9,4,5,3,2,0,44];
[0,2,8].reduce(function(p,c,i,arr){return p && (a.indexOf(c)>-1) },true)
//true
[0,2,8,45].reduce(function(p,c,i,arr){return p && (a.indexOf(c)>-1) },true)
//false
[0,2,8,44].reduce(function(p,c,i,arr){return p && (a.indexOf(c)>-1) },true)
//true
Works fine!
Is it smart enough to stop when callback fn returns false the first time ?
BTW that code checks if array 'a' contains everything array 'arr' contains .
Is it smart enough to stop when callback fn returns false the first time ?
No. The return value of the callback just becomes the value of its first parameter in the next iteration.
For example, in this call:
[0,2,8,45].reduce(function(p,c,i,arr){return p && (a.indexOf(c)>-1) },true)
In each iteration, these are the values of p, c, and i (arr is always [0,2,8,45]):
p c i return
true 0 0 true
true 2 1 true
true 8 2 true
true 45 3 false
The last return value is the final return value of reduce. It will always iterate over all values in the array.
~~~~~~~~~~~~~~~~~~~~~~~~~~
If you want something that stops on the first false, use every:
[0,45,2].every(function(c,i){return a.indexOf(c)>-1 }) // false. Stops on 45
No.
The reduce() function doesn't know what your callback does; it has no idea it's always short-circuiting.
Call every() instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With