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

我有一个像这样的数组


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}],

    ...

  ]


ITMISS
浏览 96回答 2
2回答

四季花海

您可以通过查看每个槽的总和来找到下一个槽。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 }],&nbsp; &nbsp; sum = 4,&nbsp; &nbsp; result = array.reduce((r, o) => {&nbsp; &nbsp; &nbsp; &nbsp; const temp = r.find(a => a.reduce((s, { size }) => s + size, 0) + o.size <= sum);&nbsp; &nbsp; &nbsp; &nbsp; if (temp) temp.push(o);&nbsp; &nbsp; &nbsp; &nbsp; else r.push([o]);&nbsp; &nbsp; &nbsp; &nbsp; return r;&nbsp; &nbsp; }, []);console.log(result);.as-console-wrapper { max-height: 100% !important; top: 0; }

慕森卡

我的方式...const array =&nbsp;&nbsp; &nbsp; &nbsp; [ { id: 1, size: 1 }&nbsp;&nbsp; &nbsp; &nbsp; , { id: 2, size: 2 }&nbsp;&nbsp; &nbsp; &nbsp; , { id: 3, size: 4 }&nbsp;&nbsp; &nbsp; &nbsp; , { id: 4, size: 1 }&nbsp;&nbsp; &nbsp; &nbsp; , { id: 5, size: 2 }&nbsp;&nbsp; &nbsp; &nbsp; , { id: 6, size: 3 }&nbsp;&nbsp; &nbsp; //&nbsp; , ...&nbsp; &nbsp; &nbsp; ]&nbsp; , szMax&nbsp; = array.reduce((t,c)=>Math.max(t,c.size),0)&nbsp; , temp&nbsp; &nbsp;= array.map(e=>({...e}))&nbsp; , result = []&nbsp; ;while (temp.length > 0)&nbsp; {&nbsp; let sz = szMax&nbsp; &nbsp; , nv = []&nbsp; &nbsp; ;&nbsp; while( sz > 0 )&nbsp; &nbsp; {&nbsp; &nbsp; let idx = temp.findIndex(x=>x.size <= sz)&nbsp; &nbsp; if (idx===-1) break&nbsp; &nbsp; nv.push( temp[idx] )&nbsp; &nbsp; sz -= temp[idx].size&nbsp; &nbsp; temp.splice(idx,1)&nbsp; &nbsp; }&nbsp; result.push([...nv])&nbsp; nv = []&nbsp; }console.log( result ).as-console-wrapper{max-height:100% !important;top: 0;}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript