Given the following arrays:
const x = [2, 14, 54, 109, 129, 136, 165, 312, 320, 330, 335, 348, 399, 440, 450, 461, 482, 501, 546, 547, 549, 559, 582, 584, 615, 620, 647, 682];
const y = [539, 681, 682, 683];
Using node v 7.3.0 I observe the following unexpected behavior:
[> x.find(y.includes, y);
undefined
[> y.find(x.includes, x);
682
Sample Snippet:
const x = [2, 14, 54, 109, 129, 136, 165, 312, 320, 330, 335, 348, 399, 440, 450, 461, 482, 501, 546, 547, 549, 559, 582, 584, 615, 620, 647, 682];
const y = [539, 681, 682, 683];
console.log(x.find(y.includes, y))
console.log(y.find(x.includes, x))
However code like x.find(element => y.includes(element)); always finds the element as expected.
I don't get why the two calls that just use find and includes would ever yield different results and would be delighted if someone knows an explanation.
The reason x.find(y.includes, y); is returning undefined is because of arguments passed in function.
Callback of Array.find expects 3 values viz., item, index, array and callback of Array.includes expects 2 arguments, viz., item, fromIndex.
Basically, your current index will be treated as fromIndex in Array.includes and will skip elements before it.
So after four iterations would look like, Array.includes will look for values after 4th element and y does not have them. Hence it returns undefined.
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