我有一个值数组,我需要将它们分成总值的块。每个块的总值不应高于4.
var arr = [1, 2, 4, 1, 1, 4, 2, 2, 1, 4];
这应该是:
var chunks = [[1, 2, 1], [4], [1, 2, 1], [4], [2], [4];
所以我需要将原始数组的所有值拆分成可变大小的块,但在这种情况下它的总值不应该高于4。
答案 0 :(得分:1)
这样的东西?
var arr = [1, 2, 4, 1, 1, 4, 2, 2, 1, 4];
var max = 4;
var chunks = [];
arr.forEach(x => {
// get the first chunk that the value can be added to
var chunk = chunks.find(c => {
// calculate sum of chunk
var sum = c.reduce((a, b) => a + b);
// return true if the sum of the chunk + current value in array iteration is less than max
return sum + x <= max;
});
if (chunk)
chunk.push(x); // found a chunk. Add value to that.
else
chunks.push([x]); // Can't be added to existing chunks. Create new one.
});
console.log(chunks);
&#13;