gpt4 book ai didi

javascript - 如何使用每个数组记录的多个对象对 JavaScript 或 jQuery 中的数组进行排序

转载 作者:行者123 更新时间:2023-11-30 07:51:53 24 4
gpt4 key购买 nike

在您可能会否决我之前:我已经检查了围绕此问题的所有现有解决方案,但没有一个与此类似。

我想按 image.name(JavaScript 或 jQuery)的字母顺序对这个数组进行排序:

var myArray = [{
creator: {
"firstname": "Sally",
familyname: "Bloomfield"
},
location: {
"lat": 12.123,
lng: 8.846
},
image: {
name: "Hello World",
size: "50x80"
}
},
{
creator: {
firstname: "Bob",
familyname: "Jones"
},
location: {
lat: 31.593,
lng: 96.376
},
image: {
name: "Flowerpower",
size: "40x50"
}
},
{
creator: {
firstname: "John",
familyname: "Walker"
},
location: {
lat: 27.184,
lng: 123.120
},
image: {
name: "Guiness",
size: "33x66"
}
}
];

排序后的数组输出:

[{
creator: {
firstname: "Bob",
familyname: "Jones"
},
location: {
lat: 31.593,
lng: 96.376
},
image: {
name: "Flowerpower",
size: "40x50"
}
},
{
creator: {
firstname: "John",
familyname: "Walker"
},
location: {
lat: 27.184,
lng: 123.120
},
image: {
name: "Guiness",
size: "33x66"
}
},
{
creator: {
firstname: "Sally",
familyname: "Bloomfield"
},
location: {
lat: 12.123,
lng: 8.846
},
image: {
name: "Hello World",
size: "50x80"
}
}
]

所以第一张图片 Flowerpower 然后是 Guiness 然后是 Hello World。

Javascript 的现有排序功能无法处理这个问题,因为我已经尝试过了。甚至可以对这样的结构进行排序吗?

感谢任何帮助。

最佳答案

您可以在对字符串进行排序时使用 localeCompare。然后它只是使用 Array.sort() 的一行:

var myArray = [{creator: { "firstname": "Sally", familyname: "Bloomfield"},location: { "lat": 12.123, lng: 8.846},image: {name: "Hello World", size: "50x80"}},{creator: { firstname: "Bob", familyname: "Jones"},location: { lat: 31.593, lng: 96.376},image: {name: "Flowerpower", size: "40x50"}},{creator: { firstname: "John", familyname: "Walker"},location: { lat: 27.184, lng: 123.120},image: {name: "Guiness", size: "33x66"}}];

myArray.sort((a,b) => a.image.name.localeCompare(b.image.name))
console.log(myArray)

关于javascript - 如何使用每个数组记录的多个对象对 JavaScript 或 jQuery 中的数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51433642/

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