gpt4 book ai didi

javascript - JS 中对象数组按两个值排序

转载 作者:行者123 更新时间:2023-12-02 20:54:43 24 4
gpt4 key购买 nike

我有以下对象数组

var parameter = "B001";
var my_array = [
{
"Shippment_out" : "2020-05-10",
"Batch" : "B001",
"Truck_No" : "ZB001"
},
{
"Shippment_out" : "2020-05-10",
"Batch" : "B002",
"Truck_No" : "ZB001"
},
{
"Shippment_out" : "2020-05-11",
"Batch" : "B001",
"Truck_No" : "ZB002"
},
{
"Shippment_out" : "2020-05-11",
"Batch" : "B002",
"Truck_No" : "ZB002"
},
]

我计划按参数排序,如果我将批处理号传递为 B001,则数组应先按 B001 排序,然后按 B002 排序,再加上较早的日期。在本例中为“2020-05-10”。

同样,如果我通过“B002”,然后“B002”,然后“B001”。再次提前约会。

我尝试了 my_array.sort(function (a, b) {}) 但无法实现逻辑。

最佳答案

sort 方法中,检查 a.Batch 和 b.Batch 值。
如果两个值与所需批处理相同,则根据装运进行排序。
如果其中一个值与批处理相同,则相应返回。

var my_array = [
{
Shippment_out: "2020-05-10",
Batch: "B001",
Truck_No: "ZB001"
},
{
Shippment_out: "2020-05-10",
Batch: "B002",
Truck_No: "ZB001"
},
{
Shippment_out: "2020-05-11",
Batch: "B001",
Truck_No: "ZB002"
},
{
Shippment_out: "2020-05-11",
Batch: "B002",
Truck_No: "ZB002"
}
];

const sortArray = (arr, batch) => {
return arr.sort((a, b) => {
if (a.Batch === batch && b.Batch === batch) {
return new Date(a.Shippment_out) - new Date(b.Shippment_out);
} else if (a.Batch === batch) {
return -1;
} else if (b.Batch === batch) {
return 1;
} else {
return 0;
}
});
};

console.log('B001', sortArray(my_array, "B001"));
console.log('B002', sortArray(my_array, "B002"));

关于javascript - JS 中对象数组按两个值排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61515744/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com