具有最大总和限制的组或块数组

Group or chunk array with maximum sum limit

我有一个这样的数组

const array = [{id: 1, size: 1}, {id: 2, size: 2}, {id: 3, size: 4}, {id: 4, size: 1}, {id: 5, size: 2}, {id: 6, size: 3}, ...]

我想用大小属性的最大总和对这个数组进行分组或分块(每个索引的总大小不能大于4),

所以新数组应该是这样的:

  const newArray = [
    [{id:1, size: 1}, {id:2, size: 2}, {id:4, size: 1}],
    [{id:3, size: 4}],
    [{id:5, size: 3}],
    [{id:6, size: 4}],
    ...
  ]

您可以通过查看每个插槽的总和来找到下一个插槽。

let array = [{ id: 1, size: 1 }, { id: 2, size: 2 }, { id: 3, size: 4 }, { id: 4, size: 1 }, { id: 5, size: 2 }, { id: 6, size: 3 }],
    sum = 4,
    result = array.reduce((r, o) => {
        const temp = r.find(a => a.reduce((s, { size }) => s + size, 0) + o.size <= sum);
        if (temp) temp.push(o);
        else r.push([o]);
        return r;
    }, []);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

我的方式...

const array = 
      [ { id: 1, size: 1 } 
      , { id: 2, size: 2 } 
      , { id: 3, size: 4 } 
      , { id: 4, size: 1 } 
      , { id: 5, size: 2 } 
      , { id: 6, size: 3 } 
    //  , ...
      ]
  , szMax  = array.reduce((t,c)=>Math.max(t,c.size),0)
  , temp   = array.map(e=>({...e}))
  , result = []
  ;
while (temp.length > 0)
  {
  let sz = szMax
    , nv = []
    ;
  while( sz > 0 )
    {
    let idx = temp.findIndex(x=>x.size <= sz)
    if (idx===-1) break
    nv.push( temp[idx] )
    sz -= temp[idx].size
    temp.splice(idx,1)
    }
  result.push([...nv])
  nv = []
  }

console.log( result )
.as-console-wrapper{max-height:100% !important;top: 0;}