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

198
Views
forEach returning undefined

This function goes through the arrays and in each object, add the 1st number and subtract the 2nd number

eg. number([[10,0],[3,5],[5,8]]) = (10-0) + (3-5) + (5-8) Total should equal 5

Problem: I'm using a forEach loop but it returns undefined, when I console.log the number shows 5.

var number = function(busStops){
  var total = 0;
  busStops.forEach(function(n){
    total = total + n[0] - n[1];
    return total;
  })
}
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

You could reduce the array.

const
    number = busStops => busStops.reduce((t, [a, b]) => t + a - b, 0);

console.log(number([[10, 0], [3, 5], [5, 8]]));

about 4 years ago · Juan Pablo Isaza Report

0

Just found the issue, the return should be outside the forEach loop

var number = function(busStops){
  var total = 0;
  busStops.forEach(function(n){
    total = total + n[0] - n[1];
  })
  return total;
}
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!