I want to get the sum of the values of an array only using an iterator function. Below, I get the individual values using an iterator but I'm using a for-loop to ultimately summing their values.
Is there a more elegant way to accomplish the same result using only an iterator function?
function sumArray(arr) {
function nextIterator() {
let i = 0;
var iteratorWithNext = {
next: function nextElement() {
var element = arr[i];
i++
return element;
}
}
return iteratorWithNext;
}
var iteratorWithNext = nextIterator();
let sum = 0;
for (item of arr) {
sum = sum + iteratorWithNext.next();
}
return sum;
}
const array4 = [1, 2, 3, 4];
console.log(sumArray(array4)); // -> 10