The goal is to return the sum of the numbers in the array using the forEach method. What am I doing wrong?
list = [6,7,1,3,1,17,4,12,1,5,0,13,15]
function totalPoint(array) {
let sum = 0;
array.forEach(function(number){
sum += number
return sum
})
}
totalPoint(list)
It should have the same result as this:
function totalPoints(array){
let sum = 0;
for (let i = 0; i < array.length; i++) {
sum += array[i]
}
return sum
}
4 Answers 4
Using forEach loop return sum should be outside forEach:
list = [6,7,1,3,1,17,4,12,1,5,0,13,15]
function totalPoint(array) {
let sum = 0;
array.forEach(function(number){
sum += number;
})
return sum;
}
totalPoint(list)
Comments
For each does not return anything you need to return from function:
const array = [6,7,1,3,1,17,4,12,1,5,0,13,15]
function totalPoint(array) {
let sum = 0;
array.forEach(function(number){
sum += number
})
return sum
}
console.log(totalPoint(array))
Better way is to use reduce
const array = [6,7,1,3,1,17,4,12,1,5,0,13,15]
function totalPoint(array) {
return array.reduce((sum,number) => sum + number,0)
}
console.log(totalPoint(array))
2 Comments
reduce callback. (sum, number) => sum + number is a lot more understandable than (prev, next) => prev + next.You return inside the callback (which is useless), but not at the end of the method.
function totalPoint(array) {
let sum = 0;
array.forEach(function(number){
sum += number
});
return sum;
}
list = [6,7,1,3,1,17,4,12,1,5,0,13,15]
console.log(totalPoint(list));
A simpler method would be to use Array#reduce:
function totalPoint(array) {
return array.reduce((acc,curr)=>acc + curr, 0);
}
list = [6,7,1,3,1,17,4,12,1,5,0,13,15]
console.log(totalPoint(list));
Comments
You can use Array.prototype.reduce for a simple solution:
const numbers = [6, 7, 1, 3, 1, 17, 4, 12, 1, 5, 0, 13, 15];
const sum = numbers.reduce((runningTotal, number) => runningTotal += number, 0);
console.log(`The sum is ${sum}`);
Start with the accumulator initialized to 0 then, in the callback function, increment the accumulator by the next number in the array and return.
reduceit is easier.array.reduce((total, curr) => total+=curr, 0);reduceis when you wanted an accumulated result from the array like sum, product, string concat with a filter and what not! in this use case definitely is easier as you don't have to maintain any variable.returncounts for. So far, i assumed it's just people not really trying, but by the sheer amount of issues, i may have to reconsider. The problem is solely, that yourreturnis for the callback of theforEach, and yourtotalPointdoesn't have anyreturn. Simply move thereturnto the end oftotalPoint.