简体   繁体   English

按特定单词进行排序

[英]React sorting by specific word

I am currently sorting an array of JSON objects by a number. 我目前正在按数字排序JSON对象数组。

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

This works fine, but now, I need to sort it by High, Medium, Low, and ignore the number altogether. 这工作正常,但现在,我需要按高,中,低排序,并完全忽略该数字。

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

I need to sort by the scoreValue, where it can be low, medium, or high. 我需要按scoreValue排序,它可以是低,中或高。

Any help? 有帮助吗?

Use localeCompare to sort alphabetically according to scoreValue : 使用localeCompare根据scoreValue按字母顺序排序:

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

Or, if you want a predefined order (low -> medium -> high), use an ordering map whose keys are the possible scoreValue strings and whose values are the associated order for those keys: 或者,如果您需要预定义的顺序(低 - >中 - >高),请使用一个排序映射,其键是可能的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); 

Sort with index based first array .With high to low DESC order 使用基于索引的第一个数组排序。具有从高到低的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) 

If you want to use lodash , you can do like this: 如果你想使用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));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM