gpt4 book ai didi

javascript - 对对象数组进行排序,同时将几个对象保留在最后位置

转载 作者:行者123 更新时间:2023-12-02 01:53:59 25 4
gpt4 key购买 nike

我在对对象数组进行排序时遇到了一些困难。目前我有一个像排序这样的数据集

[
{
"index":"football",
"values":0.3,
"id":"1"
},
{
"index":"Unknown",
"values":0.5,
"id":"2"
},
{
"index":"golf",
"values":0.1,
"id":"3"
},
{
"index":"cricket",
"values":0.222,
"id":"4",
},
{
"index":"Other",
"values":0.333,
"id":"5"
},
{
"index":"netball",
"values":0.753,
"id":"6",
},
]

我想做的是根据它们的值对其进行排序,最高的在最上面。为此,我做了

myDataSet.sort((a, b) => parseFloat(b.values) - parseFloat(a.values));

这似乎有效。然而,这是我正在努力解决的第二部分。无论它按什么顺序排序,我总是需要其他从底部数第二个和未知底部。所以上面应该变成这样

[
{
"index":"netball",
"values":0.753,
"id":"6",
},
{
"index":"football",
"values":0.3,
"id":"1"
},
{
"index":"cricket",
"values":0.222,
"id":"4",
},
{
"index":"golf",
"values":0.1,
"id":"3"
},
{
"index":"Other",
"values":0.333,
"id":"5"
},
{
"index":"Unknown",
"values":0.5,
"id":"2"
},
]

我尝试使用过滤器,这似乎将它们放在底部,但其余的不再排序

myDataSet.filter((e) => e.index === 'Other')
.filter((e) => e.index === 'Unknown')
.sort((a, b) => parseFloat(b.values) - parseFloat(a.values));

如何根据它们的值进行排序,但将“其他”和“未知”保留在底部?

谢谢

最佳答案

我建议创建一个自定义函数来确定排序顺序,例如 getSortValue(),然后使用 Array.sort():

let a = [ { "index":"football", "values":0.3, "id":"1" }, { "index":"Unknown", "values":0.5, "id":"2" }, { "index":"golf", "values":0.1, "id":"3" }, { "index":"cricket", "values":0.222, "id":"4", }, { "index":"Other", "values":0.333, "id":"5" }, { "index":"netball", "values":0.753, "id":"6", }, ] 

function getSortValue(obj) {
const key = obj.index.toLowerCase();
return { "unknown": -2, "other": -1 }[key] || obj.values;
}

console.log(a.sort((a,b) => getSortValue(b) - getSortValue(a)));
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - 对对象数组进行排序,同时将几个对象保留在最后位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69841690/

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