如果项目总和,如何将项目添加到数组中

时间:2018-02-10 01:23:53

标签: javascript arrays

我有这个数组:

var mes_dias = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];

我想知道是否有某种方式创建一个新数组只有当它们的总和小于使用循环或其他东西的全局数组时,例如

var dia = 122;
var dia_new = [31, 28, 31, 30]; //This because they sum less than the given var (dia).

感谢您的回答

4 个答案:

答案 0 :(得分:1)

  • 使用Javascript for-loop并在每次迭代中检查计数。
  • 如果计数小于dia,请将该号码推入array
for(var i = 0; i < mes_dias.length && (count + mes_dias[i] < dia); i++)

&#13;
&#13;
var mes_dias = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
var dia = 122;
var count = 0;
var array = [];

for(var i = 0; i < mes_dias.length && (count + mes_dias[i] < dia); i++) {
  count += mes_dias[i];
  array.push(mes_dias[i]);
}
console.log(array);
&#13;
.as-console-wrapper {
  max-height: 100% !important
}
&#13;
&#13;
&#13;

如果dia是一个数字数组,其sum是新数组的最大天数:

reduce函数会对array_dia中的元素求和。

var dia = array_dias.reduce((a, n) => a += n, 0);

&#13;
&#13;
var mes_dias = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
var array_dias = [30, 30, 31, 31];

var dia = array_dias.reduce((a, n) => a += n, 0);
console.log(dia)

var count = 0;
var array = [];

for(var i = 0; i < mes_dias.length && (count + mes_dias[i] < dia); i++) {
  count += mes_dias[i];
  array.push(mes_dias[i]);
}
console.log(array);
&#13;
.as-console-wrapper {
  max-height: 100% !important
}
&#13;
&#13;
&#13;

答案 1 :(得分:1)

您可以将reduce数组转换为新数组:

let mes_dias = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];

let dia = 120;

let dia_new = mes_dias.reduce( (dia_acc, dias) => {
    dia -= dias;
    if (dia >= 0)
        dia_acc.push(dias);
    return dia_acc;
}, []);

编辑1:基于Angel Politis' answer,另一个优雅的解决方案可以是:

let dia_new = mes_dias.slice(0, mes_dias.findIndex( (dias) => (dia -= dias) < 0));

编辑2:基于Ele's answer,这种方式提供相同(如果不是更好)的性能,并且在我看来更具可读性。请记住,在最坏的情况下,我们循环12次。

let array = [],
    sum = 0;
// Add days until they sum to more than 'dia'
for(let i = 0; i < mes_dias.length; ++i) {
    sum += mes_dias[i];
    if (sum > dia)
        break;
    array.push(mes_dias[i]);
}

答案 2 :(得分:0)

实现目标的一种方法是使用循环:

  • 逐步总结mes_dias
  • 的元素
  • 缓存最后一个元素的索引,如果sum <= dia

然后,您可以使用slice获取数组的部分,直到last索引。

<强>段:

var
  arr = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],   // mes_dias
  max = 122,                                                // dia
  last,
  newArr;

/* Iterate over every element of the array until sum > max and save the index. */
for (let i = 0, sum = 0, l = arr.length; i < l && sum <= max; sum += arr[++i]) {
  last = i;
}

/* Get the portion of the array until the index. */
newArr = arr.slice(0, last);

/* Log the result. */
console.log(newArr);

答案 3 :(得分:-1)

  var mes_dias = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];

  var dia = 122;
  var total = 0;
  var newarray = new Array();

  for(var i = 0; i < mes_dias.length && (total + mes_dias[i]) <= dia; i++) {
    newarray.push(mes_dias[i]);
    total = total + mes_dias[i];
    console.log(newarray);
  }