[英]Sorting and Array alphabetically
我有一个数组,我试图按描述的字母顺序排序,不幸的是它什么也没做。
我相信我的代码是正确的,因为它以前工作过,也许我遗漏了一些基本的东西,但我看不到它。
这是数组
{
status:200
content:{
records:[
0:{
id:"recCmTdywUZc3mRYr"
createdTime:"2023-01-28T22:24:08.000Z"
fields:{
Description:"Apple"
Qty:9
}
}
1:{
id:"recDg7dLnRsdwfvbc"
createdTime:"2023-01-28T22:24:08.000Z"
fields:{
Description:"Orange"
Qty:6
}
}
2:{
id:"recDhHyMIAS1qGu3E"
createdTime:"2023-01-28T22:30:56.000Z"
fields:{
Description:"Pear"
Qty:1
}
}
3:{
id:"recIMEr6bOtpS1Kdd"
createdTime:"2023-01-28T22:30:55.000Z"
fields:{
Description:"Banana"
Qty:10
}
}
]
}
}
这是我用来对数组进行排序的代码:
sorted = inputArray.items.slice();
sorted.sort((a, b) => a. Description.localeCompare(b. Description))
假设records
是一个数组,你需要得到正确的值
const data = { status: 200, content: { records: [{ id: "recCmTdywUZc3mRYr", createdTime: "2023-01-28T22:24:08.000Z", fields: { Description: "Apple", Qty: 9 } }, { id: "recDg7dLnRsdwfvbc", createdTime: "2023-01-28T22:24:08.000Z", fields: { Description: "Orange", Qty: 6 } }, { id: "recDhHyMIAS1qGu3E", createdTime: "2023-01-28T22:30:56.000Z", fields: { Description: "Pear", Qty: 1 } }, { id: "recIMEr6bOtpS1Kdd", createdTime: "2023-01-28T22:30:55.000Z", fields: { Description: "Banana", Qty: 10 } }] } }, records = data.content.records.slice(); records.sort((a, b) => a.fields.Description.localeCompare(b.fields.Description)); console.log(records)
.as-console-wrapper { max-height: 100%;important: top; 0; }
为什么sorted = inputArray.items.slice()
? 使用您发布的结构,它应该是sorted = inputArray.content.records.slice()
进而
sorted.sort((a, b) => a.fields.Description.localeCompare(b.fields.Description))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.