gpt4 book ai didi

javascript - Javascript 中的自定义排序数组

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

假设我有以下数组:

[
{
"key":"Certified?",
"value":"Yes"
},
{
"key":"Language",
"value":"EN"
},
{
"key":"Training-Place",
"value":"City"
}
]

我想按照Language的特定顺序对其进行排序, Certified? , Training-Place ,我怎样才能实现这一目标?最好我能够定义排序:

["Language", "Certified?", "Training-Place"]

非常感谢,非常感谢您的帮助。

最佳答案

您可以简单地使用Arrays.sort()并使用顺序数组按照顺序数组指定的顺序对数组进行排序。

尝试以下操作:

var arr = [ { "key":"Certified?", "value":"Yes" }, { "key":"Language", "value":"EN" }, { "key":"Training-Place", "value":"City" }, { "key":"Training-Place", "value":"aaa" }, { "key":"Language", "value":"bbb" }];

var order = ["Language", "Certified?", "Training-Place"];

arr.sort((a,b)=> order.indexOf(a.key) - order.indexOf(b.key));

console.log(arr);

关于javascript - Javascript 中的自定义排序数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51502766/

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