【问题标题】:How to transform array of object into more advanced array [closed]如何将对象数组转换为更高级的数组[关闭]
【发布时间】:2019-02-09 05:27:27
【问题描述】:

我正在寻找解决我在 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 个重量)

【问题讨论】:

  • 发布的问题似乎根本不包括任何解决问题的尝试。 StackOverflow 期待您 try to solve your own problem first,因为您的尝试有助于我们更好地了解您想要什么。请编辑问题以显示您尝试过的内容,以说明您在minimal reproducible example 中遇到的特定问题。欲了解更多信息,请参阅How to ask good questions 并拨打tour
  • Knapsack problem你的问题不是那么小
  • 什么决定了第一个对象中的哪个进入哪个“加载”数组?
  • 正如@CertainPerformance 提到的,你应该先尝试解决这个问题,所以我会给你一些建议。 1. 创建一个新的空数组,您可以插入负载。 2. 遍历原始数组。 3. 创建一个保存总金额的变量 4. 检查总金额的值,如果合适就插入。
  • 没关系。我应该首先检查,添加到第一个订单对象(加载数组),然后检查第二个做同样的事情,第三个当第一次加载的总重量大于 1000 时创建新的订单并加载。如果输入数组有超过 3 个对象,它应该工作相同(二阶不应该超过 1000 个)

标签: javascript arrays node.js object reduce


【解决方案1】:

您可以使用 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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-05
    • 1970-01-01
    • 2021-12-07
    • 2018-12-21
    • 1970-01-01
    • 2019-09-15
    • 2011-09-04
    相关资源
    最近更新 更多