gpt4 book ai didi

arrays - 按递减或递增顺序按数字字段对数组 Angular 7 进行排序

转载 作者:行者123 更新时间:2023-12-04 14:41:00 26 4
gpt4 key购买 nike

我需要帮助,我需要按 PendingQuantity 字段对数组进行排序。我有负数和正数。所以我的代码:

this.data.Products.sort(obj => obj.PendingQuantity);

所以我的数组

"Products": [
{
"ProductCode": "MC30180",
"Description": "Description_1",
"NationalCode": "N.C. 0965",
"PendingQuantity": 20,
"toBeScanned": true
},
{
"ProductCode": "Name_2",
"Description": "Description_2",
"NationalCode": "N.C. 0382",
"PendingQuantity": -3,
"toBeScanned": false
},
{
"ProductCode": "Name_3",
"Description": "Description_3",
"NationalCode": "N.C. 8913",
"PendingQuantity": 25,
"toBeScanned": false
}
]

我想要的顺序是:

"Products": [
{
"ProductCode": "MC30180",
"Description": "Description_1",
"NationalCode": "N.C. 0965",
"PendingQuantity": -3,
"toBeScanned": true
},
{
"ProductCode": "Name_2",
"Description": "Description_2",
"NationalCode": "N.C. 0382",
"PendingQuantity": 25,
"toBeScanned": false
},
{
"ProductCode": "Name_3",
"Description": "Description_3",
"NationalCode": "N.C. 8913",
"PendingQuantity": 20,
"toBeScanned": false
}
]

最佳答案

您可以将其用于订单 asc product = product.sort((a, b) => a.PendingQuantity - b.PendingQuantity);

如果您想按 desc 订购,请使用 product = product.sort((a, b) => b.PendingQuantity - a.PendingQuantity);

更新:

如果您显示自定义顺序如-3、25、20,您可以处理排序条件。

product = product.sort((a, b) => { if (a.PendingQuantity < 0) {return -1; } if (b.PendingQuantity <0 ) {return 1;} return b.PendingQuantity - a.PendingQuantity });

let product = [
{
"ProductCode": "MC30180",
"Description": "Description_1",
"NationalCode": "N.C. 0965",
"PendingQuantity": 20,
"toBeScanned": true
},
{
"ProductCode": "Name_2",
"Description": "Description_2",
"NationalCode": "N.C. 0382",
"PendingQuantity": -3,
"toBeScanned": false
},
{
"ProductCode": "Name_3",
"Description": "Description_3",
"NationalCode": "N.C. 8913",
"PendingQuantity": 25,
"toBeScanned": false
}
];


product = product.sort((a, b) => a.PendingQuantity - b.PendingQuantity);
product = product.sort((a, b) => { if (a.PendingQuantity < 0) {return -1; } if (b.PendingQuantity <0 ) {return 1;} return b.PendingQuantity - a.PendingQuantity });

console.log(product);

关于arrays - 按递减或递增顺序按数字字段对数组 Angular 7 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55415984/

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