1

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
leonardofed
  • 936
  • 2
  • 9
  • 24
  • 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. – ASDFGerte Jul 30 '18 at 18:06
  • Possible duplicate of [How to find the sum of an array of numbers](https://stackoverflow.com/questions/1230233/how-to-find-the-sum-of-an-array-of-numbers) – Sphinx Jul 30 '18 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? – Bergi Jul 30 '18 at 18:11
  • Iterators are used because they can yield multiple values, which makes certainly no sense with only one value – Jonas Wilms Jul 30 '18 at 18:14
  • are you looking for recursive function? var sumFunc = function(el){ if(el){ sum=sum+el; sumFunc(nextIterator().next()); } else{return sum;} } – Rahul R. Jul 30 '18 at 18:23

3 Answers3

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
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
1

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)

SamVK
  • 3,077
  • 1
  • 14
  • 19
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
Régis B.
  • 187
  • 1
  • 9