【发布时间】:2019-12-07 14:49:53
【问题描述】:
所以我需要为这个数组中的fuel.name值添加排序功能...
const orders = [
{
"_id":"5d14a31490fb1e0012a3d2d8-1",
"orderId":"0JL5ORM0JT-1",
"created":"2019-06-27T11:05:56.377Z",
"createdDate":"2019-06-27T09:05:56.377Z",
"offers":[
{
"price":95.27,
"fuel":{
"_id":"5ce13948eaef5200113b0de8",
"name":"Diesel B7",
"description":"Diesel",
"lpt":0,
"duty":0,
"type":"SPOT",
"created":"2019-05-19T11:08:56.417Z"
}
},
{
"price": 95.27,
"fuel": {
"_id": "5ce13948eaef5200113b0de8",
"name": "Petrol",
"description": "Petrol",
"lpt": 0,
"duty": 0,
"type": "SPOT",
"created": "2019-05-19T11:08:56.417Z"
}
},
{
"price": 95.27,
"fuel": {
"_id": "5ce13948eaef5200113b0de8",
"name": "Fossil Fuel",
"description": "Fossil Fuel",
"lpt": 0,
"duty": 0,
"type": "SPOT",
"created": "2019-05-19T11:08:56.417Z"
},
}
]
}
]
我希望“offers”对象根据“fuel.name”重新排序
orders.sort((a: any, b: any) => a.offers[0].fuel.name.toUpperCase().localCompare(b.offers[0].fuel.name))
当我控制台记录上述内容时,它只会以相同的顺序返回数据。我在下面设置了一个小提琴来复制我遇到的问题。
这是fiddle
【问题讨论】:
-
请发minimal reproducible example,包括一个有效的Javascript语法输入结构(问题中的代码不是有效的Javascript语法)
-
@CertainPerformance 这样更好吗?
-
如果可以,请将您的实际代码作为文本编辑到您的问题中 - 代码单独的图像是tedious and difficult,可以使用和调试.它会迫使那些本来愿意帮助你的人先transcribe your image,这是浪费时间。
-
我在@CertainPerformance 下方添加了一个小提琴
-
你有一个错字。这是
localeCompare而不是localComapre。您添加的小提琴不会重现您发布的错误。另外,您是要对嵌套的offers数组进行排序,还是根据offers[0].fuel.name对orders数组进行排序?
标签: javascript arrays sorting ecmascript-6 functional-programming