Search code examples
javascriptarraysdivide

Dividing numbers between each other in a Javascript array


I have an array of randomly generated numbers. I want to create a function that divides all those numbers. Basically, assuming that I have 5 numbers in the array [5, 7, 6, 8, 2], I want the output to be equal to 5 / 7 / 6 /8 / 2

array = [5, 7, 6, 8, 2];

var total = 1;    
for(var i = 0; i < array.length; i++) {
total = array[i] / total; 
}

return total;

This is what I did so far, but the output isn't the correct one. Any idea where I am doing wrong?


Solution

  • You've basically got your math backwards. With your approach, you want to progressively divide total, rather than progressively dividing by total.

    var total = array[0];
    for (var i = 1; i < array.length; i++) 
        total = total / array[i];
    return total;