ogot ogot - 1 year ago 83
Javascript Question

Javascript reduce() until sum of values < variable

I am fetching an array of video durations (in seconds) from a JSON file in Javascript, that, to simplify, would look like this:

array = [30, 30, 30]

I would like to add each value to the previous value until a condition is met (the sum being less than a variable x) and then to get both the new value and the index position in the array of the video to play.

For example if x=62 (condition), I would like the first two values in the array to be added (from my understanding reduce() is appropriate here), and the index = 2 (the second video in the array).

I've got the grasp of reduce():

var count = array.reduce(function(prev, curr, index) {
console.log(prev, curr, index);
return prev + curr;

But can't seem to get beyond this point.. Thanks

Answer Source

You could use Array#some, which breaks on a condition.

var array = [30, 30, 30],
    x = 62,
    sum = 0;
array.some(function (a, i) {
    index = i;
    if (sum + a > x) {
        return true;
    sum += a;

console.log(index, sum);

With a compact result and this args

var array = [30, 30, 30],
    x = 62,
    result = { index: -1, sum: 0 };
array.some(function (a, i) {
    this.index = i;
    if (this.sum + a > x) {
        return true;
    this.sum += a;
}, result);


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download