0

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; }) } 
2
  • Array#forEach does not use any return value. take Array#reduce instead. Commented Jun 30, 2022 at 20:55
  • 1
    The return statement should not be in the loop. You can try to put it after the closing bracket and parenthesis. Commented Jun 30, 2022 at 21:01

2 Answers 2

2

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]]));

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

Comments

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; } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.