2 回答
TA贡献1811条经验 获得超5个赞
您可以通过查看每个槽的总和来找到下一个槽。
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; }
TA贡献1806条经验 获得超8个赞
我的方式...
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;}
添加回答
举报