简体   繁体   中英

React sorting by specific word

I am currently sorting an array of JSON objects by a number.

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.

Any help?

Use localeCompare to sort alphabetically according to 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:

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

 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:

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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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