我有一个对象数组,我需要将此数组拆分为多个数组。如果元素计数之和<= 500,则以数组形式返回这些对象。
const array = [{idx: 1, count: 100}, {idx: 2, count: 200}, {idx: 3, count: 200}, {idx: 4, count: 100}]
//Expected Result: array of arrays
// [[{idx: 1, count: 100}, {idx: 2, count: 200}, {idx: 3, count: 200}], [{idx: 4, count: 100}]]
答案 0 :(得分:2)
您可以简单地使用reduce进行操作:
const array = [{idx: 1, count: 100}, {idx: 2, count: 200}, {idx: 3, count: 200}, {idx: 4, count: 100}]
const result = array.reduce((carry, item) => {
if (!carry.array.length || carry.count + item.count > 500) {
carry.array.push([item]);
carry.count = item.count;
} else {
carry.array[carry.array.length - 1].push(item);
carry.count += item.count;
}
return carry;
}, {array: [], count: 0}).array;
console.log(result);
答案 1 :(得分:1)
这可以通过生成器很好地解决:
function* groupTill(arr, predicate) {
let acc = [], pred = predicate();
for(const el of arr) {
if(!pred(el)) {
yield acc; acc = []; pred = predicate();
}
acc.push(el);
}
yield acc;
}
const result = [...groupTill(input, (total = 0) => ({ count }) => (total += count) < 500)];
答案 2 :(得分:0)
您可以使用forEach
遍历数组并具有两个单独的变量。一个用于结果数组,另一个用于保存count
const array = [{idx: 1, count: 100}, {idx: 2, count: 200}, {idx: 3, count: 200}, {idx: 4, count: 100}]
const res = [[]]; //initialize the result array with initial subarray
let count = 0; //initialize the count to zero
//Loop through the elements of array.
array.forEach(x => {
res[res.length - 1].push(x); //Add the the current element to the last sub array
count += x.count //increase the temporary count
//if count exceeds 500
if(count >= 500){
//add another sub array to the end of final array
res.push([]);
//Reset the count to 0
count = 0;
}
});
console.log(res);
答案 3 :(得分:0)
您可以将reduce
与标志一起使用(这些标志用于跟踪是否需要增加索引)
const array = [{idx: 1, count: 100}, {idx: 2, count: 200}, {idx: 3, count: 200}, {idx: 4, count: 100}]
let splitter = (arr) => {
let index = 0,
total = 0
return arr.reduce((op, inp) => {
if ((total + inp.count) > 500) {
index++;
total = 0;
}
total += inp.count
op[index] = op[index] || []
op[index].push(inp)
return op
}, [])
}
console.log(splitter(array))