Reputation: 408
I met an unexpected result when I count the number of common elements in two arrays. When I use reduce
function, it doesn't work. But filter
version returns correct result. I want to know what's wrong with my reduce
version.
var ls = [1, 2, 3, 4, 5];
var ms = [4, 5, 6, 1, 2];
console.log(ls.reduce((acc, e) => (ms.includes(e) ? 1 + acc : 0), 0));
// 2, incorrect
console.log(ls.filter(e => ms.includes(e)).length);
// 4, correct
Upvotes: 1
Views: 704
Reputation: 136114
Because in your reduce
version, when the element is not found, you reset the acc
back to zero instead of returning it as is
var ls = [1, 2, 3, 4, 5];
var ms = [4, 5, 6, 1, 2];
console.log(ls.reduce((acc, e) => (ms.includes(e) ? 1 + acc : acc), 0));
// -----------------------------------------------------------^ here
// 4, now corrected
Upvotes: 2
Reputation: 11
When your callback function that's the first parameter of the reduce function hits the third item in the ls array, "3", it finds that it's not a member of the ms array. This causes the ternary operator to return the right hand expression 0, which resets your accumulator variable, acc. This will restart the count at 0.
Instead, you should return the current value of the accumulator variable instead of 0 like this:
console.log(ls.reduce(acc,e) => (ms.includes(e) ? 1 + acc: acc), 0));
That will give you the correct count of 4 matching elements.
Upvotes: 0