Javascript 按特定单词排序
我目前正在按数字对JSON对象数组进行排序Javascript 按特定单词排序,javascript,reactjs,Javascript,Reactjs,我目前正在按数字对JSON对象数组进行排序 myArray.sort((a, b) => a.scorePriority - b.scorePriority) 这很好,但现在,我需要按高、中、低对其进行排序,并完全忽略数字 [ { scorePriority: 10, scoreValue: "low" }, { scorePriority: 3, scoreValue: "high" }, { scorePriority: 10, scoreValue: "me
myArray.sort((a, b) => a.scorePriority - b.scorePriority)
这很好,但现在,我需要按高、中、低对其进行排序,并完全忽略数字
[
{ scorePriority: 10, scoreValue: "low" },
{ scorePriority: 3, scoreValue: "high" },
{ scorePriority: 10, scoreValue: "medium" }
]
我需要按scoreValue进行排序,它可以是低、中或高
有什么帮助吗?用于根据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数组=[
{scoreValue:'低',scorePriority:0},
{scoreValue:'中等',scorePriority:5},
{scoreValue:'低',scorePriority:6},
{scoreValue:'高',scorePriority:2},
{scoreValue:'medium',scorePriority:0},
{scoreValue:'高',scorePriority:10}
];
const sorted1=[…数组].sort((a,b)=>a.scoreValue.localeCompare(b.scoreValue));
控制台日志(1);
常量sorted2=[…数组].sort((a,b)=>{
常量顺序={“低”:0,“中”:1,“高”:2};
退货订单[a.scoreValue]-订单[b.scoreValue];
});
控制台日志(2)代码>使用基于索引的第一个数组进行排序。使用从高到低的DESC
顺序
var ind=[“高”、“中”、“低”];
var arr=[{scorePriority:10,scoreValue:“低”},{scorePriority:10,scoreValue:“高”}]
arr=arr.sort((a,b)=>{
返回ind.indexOf(a.scoreValue)-ind.indexOf(b.scoreValue)
})
console.log(arr)
如果要使用,可以执行以下操作:
const items = [
{ scoreValue: 'low', scorePriority: 0 },
{ scoreValue: 'medium', scorePriority: 5 },
{ scoreValue: 'low', scorePriority: 6 },
{ scoreValue: 'high', scorePriority: 2 },
{ scoreValue: 'medium', scorePriority: 0 },
{ scoreValue: 'high', scorePriority: 10 }
];
_.sortBy(items, item => ["high", "medium", "low"].indexOf(item.scoreValue));
虽然你没有错,但我从prasanth那里找到了更容易满足我需要的答案。谢谢你的帮助@索尔德福。永远欢迎