gpt4 book ai didi

javascript - 按特定单词 react 排序

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:10:34 25 4
gpt4 key购买 nike

我目前正在按数字对 JSON 对象数组进行排序。

myArray.sort((a, b) => a.scorePriority - b.scorePriority)

这工作正常,但现在,我需要按高、中、低对它进行排序,并完全忽略数字。

[
{ scorePriority: 10, scoreValue: "low" },
{ scorePriority: 3, scoreValue: "high" },
{ scorePriority: 10, scoreValue: "medium" }
]

我需要按分数值排序,它可以是低、中或高。

有什么帮助吗?

最佳答案

使用localeCompare根据 scoreValue 按字母顺序排序:

array.sort((a, b) => a.scoreValue.localeCompare(b.scoreValue))

或者,如果您想要一个预定义的顺序(低 -> 中 -> 高),请使用一个排序映射,其键是可能的 scoreValue 字符串,其值是这些键的关联顺序:

array.sort((a, b) => {
const orders = { 'low': 0, 'medium': 1, 'high': 2 };
return orders[a.scoreValue] - orders[b.scoreValue];
});

const array = [
{ scoreValue: 'low', scorePriority: 0 },
{ scoreValue: 'medium', scorePriority: 5 },
{ scoreValue: 'low', scorePriority: 6 },
{ scoreValue: 'high', scorePriority: 2 },
{ scoreValue: 'medium', scorePriority: 0 },
{ scoreValue: 'high', scorePriority: 10 }
];

const sorted1 = [...array].sort((a, b) => a.scoreValue.localeCompare(b.scoreValue));
console.log(sorted1);

const sorted2 = [...array].sort((a, b) => {
const orders = { 'low': 0, 'medium': 1, 'high': 2 };
return orders[a.scoreValue] - orders[b.scoreValue];
});
console.log(sorted2);

关于javascript - 按特定单词 react 排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55123569/

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