React按特定单词排序

3
我正在对一个JSON对象的数组按照数字排序。
myArray.sort((a, b) => a.scorePriority - b.scorePriority)

这个可以正常工作,但现在我需要按高、中、低排序,并完全忽略数字。
[
    { scorePriority: 10, scoreValue: "low" },
    { scorePriority: 3, scoreValue: "high" },
    { scorePriority: 10, scoreValue: "medium" }
]

我需要按照scoreValue来排序,可以是低、中或高。

有什么帮助吗?

3个回答

5
使用 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);


1
虽然你没错,但我发现 Prasanth 的答案更符合我的需求。感谢你的帮助! - letsCode

3

按照第一个数组的索引进行排序。按高到低(DESC)的顺序

var ind = ['high', 'medium', 'low'];
var arr = [{ scorePriority: 10, scoreValue: "low" }, { scorePriority: 10, scoreValue: "high" }]

arr = arr.sort((a,b) => {
 return ind.indexOf(a.scoreValue) -ind.indexOf(b.scoreValue)
})
console.log(arr)


@soldfor。欢迎您的到来。 - prasanth

1
如果您想使用lodash,可以这样做:
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));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接