Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

215
Views
Counting common elements of two Arrays in JavaScript (reduce function)

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

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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

   

about 4 years ago · Juan Pablo Isaza Report

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!