我正在寻找JS中我的小问题的解决方案。 我有对象数组
[
{ "id": "id-1", "weight": 345 },
{ "id": "id-2", "weight": 500 },
{ "id": "id-3", "weight": 300 }
]
我想得到图片上的数组
[
{
"orderID" : "uniqueID",
"load" : [
{ "id" "id-1", "weight": 345 },
{ "id" "id-2", "weight": 500 },
]
},
{
"orderID" : "uniqueID",
"load" : [
{ "id" "id-3", "weight": 300 }
]
}
]
我想将包裹分成多个负载(每个负载不超过1000重量)
答案 0 :(得分:0)
您可以使用array.reduce进行分组:
var arr = [
{ "id": "id-1", "weight": 345 },
{ "id": "id-2", "weight": 500 },
{ "id": "id-3", "weight": 300 }
];
var res = arr.reduce((m, o, i) => {
var lastPushedElement = m[m.length - 1];
var totLoad = lastPushedElement.load.reduce((s, e) => s + e.weight, 0);
if ((totLoad + o.weight) <= 1000) {
lastPushedElement.load.push(o);
} else {
m.push({ orderID: i + 1, load: [o] });
}
return m;
}, [{ orderID: 0, load: [] }]);
console.log(res);