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

139
Views
How to improve forEach in JavaScript for large lists

I have a pretty big data object and every time I refresh the page I have to resume the data from that water. Is there a way I can make a forEach faster?

if (Object.keys(jsonData.data.users).length > 0) {
  Object.keys(jsonData.data.users).forEach((username) => {
    const user = jsonData.data.users[username];
    const register_date = new Date(user.register_date);

    if (register_date >= start_date && register_date <= end_date) {
      data.guestsNumber++;
    }

    actions += user.actions_per_session;

    session_duration += user.session_duration;

    data.cartViews += user.cart_views;
  })

  data.actionsPerSession = (actions / (Object.keys(jsonData.data.users).length)).toFixed(2);

  data.averageSessionDuration = (session_duration / (Object.keys(jsonData.data.users).length)).toFixed(2);
}

What ways would there be to give a better time?

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

0

In general, this looks sufficiently fast. You can take some benchmarks via jsbench.me, but I think you're going to have to look beyond the code to re-architecting overall page load times.


But here's how I'd refactor the code to squeeze out performance

You can convert if (arr.length > 0) { arr.forEach(...) } to just do arr.forEach(...). If the array is empty, forEach will just never fire the callback, but is still valid. That prevents doing Object.keys(jsonData.data.users) twice.

Also, you're calling Object.keys(jsonData.data.users) 4 different times; should be slightly faster to allocate to a variable and re-use that.

So should look like this:

var users = Object.keys(jsonData.data.users);
users.forEach((username) => {
    const user = jsonData.data.users[username];
    const register_date = new Date(user.register_date);

    if (register_date >= start_date && register_date <= end_date) {
      data.guestsNumber++;
    }

    actions += user.actions_per_session;

    session_duration += user.session_duration;

    data.cartViews += user.cart_views;
})

data.actionsPerSession = (actions / (users.length)).toFixed(2);
data.averageSessionDuration = (session_duration / (users.length)).toFixed(2);
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!