1

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

2 Answers 2

2

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

   

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.