Adamsky97
Adamsky97

Reputation: 43

Sum of array elements counted dynamic by JS/jQuery

I have loop like this:

while((numbers[0]+numbers[1]+numbers[2]+numbers[3]+numbers[4]+numbers[5]+numbers[6]
        +numbers[7]+numbers[8]+numbers[9]+numbers[10]+numbers[11]+numbers[12]+numbers[13]
        +numbers[14]+numbers[15]+numbers[16]+numbers[17]+numbers[18]+numbers[19]+numbers[20]
        +numbers[21]+numbers[22]+numbers[23]+numbers[24]+numbers[25]+numbers[26]+numbers[27]
        +numbers[28]+numbers[29]+numbers[30]+numbers[31]) != 0 )
    {
        x=Math.floor((Math.random() * 32) + 0);

        if (numbers[x]!=0) {
            $('.board').append('<div class="tile" data-icon="icon'+(numbers[x])+'" data-end="no"></div>');
            numbers[x]=0;
        } 
    }

I wanna make my while condition more sexy. I need a sum of 'numbers' elements. In loop, values of array elements are changing, so I guess I can't count it by for loop, dynamic counting is necessary. Is some function for that? I'll be grateful for any help with solution my problem.

Upvotes: 0

Views: 257

Answers (2)

Joey Ciechanowicz
Joey Ciechanowicz

Reputation: 3663

You can use reduce on an array to perform an operation sequentially on each element, and pass on the result of the previous calculation to the next one. This allows you to "sum" the array by adding each value to the previous ones.

while(numbers.reduce(function(prev, curr) {
    return prev + curr;
}, 0)) {
     // loop body
}

In es6 parlance, you can use fat arrow syntax to make this more succient:

while(numbers.reduce((p, c) => p + c, 0)) {
    // loop body
}

Upvotes: 1

Pranav C Balan
Pranav C Balan

Reputation: 115232

Use reduce() with ES6 arrow function in latest browsers

while(numbers.reduce((a,b) => a+b ) != 0 )

or with function

while(numbers.reduce(function(a,b){ return a+b }) != 0 )

For older browser check polyfill option of reduce method.

Upvotes: 2

Related Questions