0

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.

1
  • Why not use Array.prototype.reduce instead? Or a forEach? Commented May 25, 2016 at 8:49

2 Answers 2

2

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.

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

Comments

1

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
}

2 Comments

This gets even smaller in ES2015. numbers.reduce((a, b) => (a+b))
Indeed it does. I'm still a fan of passing in the initial value explicitly however

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.