简体   繁体   English

如何通过 arrays Javascript 拆分对象数组

[英]How to split an array of objects by arrays Javascript

I have an array of objects, i need to split this array to multiple arrays.我有一个对象数组,我需要将此数组拆分为多个 arrays。 If sum of element count <= 500, return these objects in array.如果元素计数的总和 <= 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}]]

This can be solved quite elegantly with generators:这可以使用生成器非常优雅地解决:

 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)];

You can simply do it using reduce:你可以简单地使用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);

You can use forEach to iterate through array and have two separate variables.您可以使用forEach遍历数组并拥有两个单独的变量。 One for the result array and another to hold the sum of count一个用于结果数组,另一个用于保存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);

You can use reduce with flags ( These are used to track whether we need to increase the index or not )您可以使用带有标志的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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM