3

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
5
  • 1
    let sum = 0; for (let val of arr) sum += val; return sum; - for ... of works on iterables, maybe i don't understand what you want, but it sounds like it already does exactly what you want. E.g. let iterable = (function*() { yield 1; yield 2; yield 3; })(); for (let val of iterable) console.log(val); works. Commented Jul 30, 2018 at 18:06
  • Possible duplicate of How to find the sum of an array of numbers Commented Jul 30, 2018 at 18:09
  • 1
    What do you mean by "using an iterator function" if not the builtin iterator feature, and why do you want to use that instead of simply iterating the array like everyone else? Commented Jul 30, 2018 at 18:11
  • Iterators are used because they can yield multiple values, which makes certainly no sense with only one value Commented Jul 30, 2018 at 18:14
  • are you looking for recursive function? var sumFunc = function(el){ if(el){ sum=sum+el; sumFunc(nextIterator().next()); } else{return sum;} } Commented Jul 30, 2018 at 18:23

3 Answers 3

4

Yup, this is the example used for reduce.

[1, 2, 3, 4].reduce((sum, number) => sum + number)

The reduce() method applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value.


Edit: If you want an empty array to evaluate to 0 (rather than error), pass an initial value:

[1, 2, 3, 4].reduce((sum, number) => sum + number, 0)

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

3 Comments

Do not forget to pass the proper initial value.
Not required. "If no initial value is supplied, the first element in the array will be used."
If no initial value is supplied, the code will not work for all valid inputs.
2

If your aim is to take an iterator and sum up all its yielded values, that can easily be done with a simple loop:

 function sum(iterator) {
   let value, done, sum = 0;
   do {
    ({value, done} = iterator.next());
    sum += value || 0;
   } while(!done)
   return sum;
}

function* iter() { yield 1; yield 2; yield 3; }
sum(iter()) // 6

Comments

0

You can use Array's reduce function to achieve this.

var a = [1, 2, 3, 4];
var sum = a.reduce( (a,b) => a + b);//sum will be 10

1 Comment

Do not forget to pass the proper initial value.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.