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

125
Views
Reducing array , modifying the accumulator

Is this way of reducing an array (counting occurrences) not recommended? I mean modifying the accumulator is maybe bad?

function countOccurrencesReduceOwn(array, searchElement) //seems to work but is maybe not recommended ?
  {
    const count = array.reduce((accumulator, currentValue) => {
      if(currentValue === searchElement)
      {
        accumulator++; //do not do this?
      }  
      return accumulator; 
    }, 0);
    return count;
  }

Another similar is the following code which does not work. It's meant for getting the largest value of the array.

function getMaxReduceOwn(array) //does not work 
  {
    if(array.length<=0)
    {
      return undefined;
    }
    const largest = array.reduce((largest, currentValue) => { 
      if(currentValue > largest)
      {  
        largest =currentValue; //do not do this?
      }
      return largest;
    }, array[0]);
  }
about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Yes, this is unusual. Apart from "modifying parameters", reduce comes from functional programming where mutable variable are despised. You should rather simply return a new value:

const count = array.reduce((accumulator, currentValue) => {
  if (currentValue === searchElement) return accumulator + 1;
  else return accumulator; 
}, 0);
const largest = array.reduce((largest, currentValue) => { 
  if (currentValue > largest) return currentValue;
  else return largest;
});

If you were to reassign the accumulator variable, there's no reason to use the reduce method at all, you could simply write a normal for loop to the same effect, which would be shorter and more idiomatic than the unusal reduce:

let count = 0;
for (const currentValue of array) {
  if(currentValue === searchElement) {
    count++;
  }
}
return count;
if (array.length <= 0) {
  return undefined;
}
let largest = array[0];
for (const currentValue of array.slice(1)) {
  if (currentValue > largest) {  
    largest = currentValue;
  }
}
return largest;
about 4 years ago · Santiago Trujillo 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!