[英]Sort array Angular 7 by number field on decreasing or increase order
我需要幫助,我需要按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);
如果product = product.sort((a, b) => b.PendingQuantity - a.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": "NC 0965", "PendingQuantity": 20, "toBeScanned": true }, { "ProductCode": "Name_2", "Description": "Description_2", "NationalCode": "NC 0382", "PendingQuantity": -3, "toBeScanned": false }, { "ProductCode": "Name_3", "Description": "Description_3", "NationalCode": "NC 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);
您可以使用Array
sort
功能
products.sort((a,b)=> a['PendingQuantity'] - b['PendingQuantity']);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.