Javascript reduce()直到值的总和<变量

时间:2016-10-27 19:10:44

标签: javascript jquery json reduce

我从Javascript中的JSON文件中获取一个视频持续时间数组(以秒为单位),为简化起见,它将如下所示:

array = [30, 30, 30]

我想将每个值添加到前一个值,直到满足条件(总和小于变量x),然后获取要播放的视频数组中的新值和索引位置。

例如,如果x = 62(条件),我想要添加数组中的前两个值(从我的理解,reduce()在这里是合适的),并且index = 2(数组中的第二个视频) )。

我已经掌握了reduce():

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

但似乎无法超越这一点..谢谢

7 个答案:

答案 0 :(得分:10)

您可以使用 Array#一些 ,在某种情况下会中断。









  var array = [30,30,30],
 x = 62,
索引,&#的xD;
 sum = 0;
 
 array.some(function(a,i){
 index = i;
 if(sum + a> x){& #xD;
返回true;
}
 sum + = a;
});
&#xA ;
 console.log(index,sum);  











结果紧凑而且这个args







& #xD;

  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){
返回true;
}
 this.sum + = a;
},结果) ;&#的xD;
&#的xD;
的console.log(结果);  
&#的xD;

&#的xD;&# XA;
&#的xD;





答案 1 :(得分:2)



var a = [2,4,5,7,8];
var index;
var result = [0, 1, 2, 3].reduce(function(a, b,i) {
  var sum = a+b;
  if(sum<11){
    index=i;
    return sum;
  }
}, 2);
console.log(result,index);
&#13;
&#13;
&#13;

答案 2 :(得分:1)

使用for循环怎么样?这是无黑客的:

function sumUntil(array, threshold) {
    let i
    let result = 0

    // we loop til the end of the array
    // or right before result > threshold
    for(i = 0; i < array.length && result+array[i] < threshold; i++) {
        result += array[i]
    }

    return {
        index: i - 1, // -1 because it is incremented at the end of the last loop
        result
    }
}

console.log(
    sumUntil( [30, 30, 30], 62 ) 
) 
// {index: 1, result: 60}

奖励:将let替换为var,它适用于IE5.5

答案 3 :(得分:0)

你可以做到

    var limit = 60;
    var array = [30,30,30];
    var count = array.reduce(function(prev, curr, index) {
      var temp = prev.sum + curr;
      if (index != -1) {
        if (temp > limit) {
          prev.index = index;
        } else {
          prev.sum = temp;
        }
      }
      return prev;
    }, {
      sum: 0,
      index: -1
    });

    console.log(count);

答案 4 :(得分:0)

这个怎么样:https://jsfiddle.net/rtcgpgk2/1/

var count = 0; //starting index
var arrayToCheck = [20, 30, 40, 20, 50]; //array to check
var condition = 100; //condition to be more than
increment(arrayToCheck, count, condition); //call function

function increment(array, index, conditionalValue) {

  var total = 0; //total to add to
  for (var i = 0; i < index; i++) { //loop through array up to index
    total += array[i]; //add value of array at index to total
  }

  if (total < conditionalValue) { //if condition is not met
    count++; //increment index
    increment(arrayToCheck, count, condition); //call function

  } else { //otherwise
    console.log('Index : ', count) //log what index condition is met
  }

}

答案 5 :(得分:0)

// define the max outside of the reduce
var max = 20;
var hitIndex;
var count = array.reduce(function(prev, curr, index) {
                let r = prev + curr;
                // if r is less than max keep adding 
                if (r < max) { 
                 return r 
                } else {
                  // if hitIndex is undefined set it to the current index
                  hitIndex = hitIndex === undefined ? index : hitIndex;
                  return prev;
                }
            });
console.log(count, hitIndex);

这将为您提供超过最大值的第一个加法的索引。您可以尝试使用index - 1作为第一个未超过它的值。

答案 6 :(得分:0)

您可以创建一个小实用程序方法reduceWhile

// Javascript reduceWhile implementation
function reduceWhile(predicate, reducer, initValue, coll) {
    return coll.reduce(function(accumulator, val) {
        if (!predicate(accumulator, val)) return accumulator;
        return reducer(accumulator, val);
    }, initValue)
};

function predicate(accumulator, val) {
    return val < 6;
}

function reducer(accumulator, val) {
    return accumulator += val;
}

var result = reduceWhile(predicate, reducer, 0, [1, 2, 3, 4, 5, 6, 7])

console.log("result", result);