wingad
wingad

Reputation: 23

Use sort to sort by preference?

I have an array of objects that returns 3 possible sensitivity values: "LOW", "MEDIUM", "HIGH". However with the code below it is sorting in "HIGH - MEDIUM and LOW" respectively in ascending order and I wish it to return "HIGH - MEDIUM and LOW". What can I fix in this code?

In this function I compare the sensitivities received in the array

orderItemsByOrderOption = (items) => {
switch (this.state.selectedOrderOption.column) {
  case "sensitivity":
    return items.sort((a, b) => {
      if (a.sensitivity > b.sensitivity) {
        return 1;
      }
      if (a.sensitivity < b.sensitivity) {
        return -1;
      }
      // a must be equal to b
      return 0;
    });

Upvotes: 2

Views: 622

Answers (3)

Tholle
Tholle

Reputation: 112887

You could create an array with desired order and use the index of your array elements' sensitivity in this array for sorting.

Example

const arr = [
  { sensitivity: "MEDIUM" },
  { sensitivity: "LOW" },
  { sensitivity: "HIGH" }
];
const order = ["HIGH", "MEDIUM", "LOW"];

arr.sort((a, b) => order.indexOf(a.sensitivity) - order.indexOf(b.sensitivity));

console.log(arr);

Upvotes: 3

Nick
Nick

Reputation: 16586

You could create a sort order lookup that maps HIGH, MEDIUM, and LOW to numeric values since sorting them alphabetically doesn't make sense.

const sensitivitySortOrder = {
  HIGH: 0,
  MEDIUM: 1,
  LOW: 2
};

orderItemsByOrderOption = (items) => {
switch (this.state.selectedOrderOption.column) {
  case "sensitivity":
    return items.sort((a, b) => {
      const aRank = sensitivitySortOrder[a.sensitivity];
      const bRank = sensitivitySortOrder[b.sensitivity];
      if (aRank > bRank) {
        return 1;
      }
      if (aRank < bRank) {
        return -1;
      }
      // a must be equal to b
      return 0;
    });

Upvotes: 0

hgb123
hgb123

Reputation: 14891

There is a way is to convert rank into numeric value and compare that value

const data = [
  { id: 1, sensitivity: "LOW" },
  { id: 2, sensitivity: "HIGH" },
  { id: 3, sensitivity: "LOW" },
  { id: 4, sensitivity: "MEDIUM" },
  { id: 5, sensitivity: "HIGH" },
  { id: 6, sensitivity: "MEDIUM" },
];

const getRankInNum = (el) =>
  ({
    HIGH: 2,
    MEDIUM: 1,
    LOW: 0,
  }[el.sensitivity] || -1);

const res = data.sort((a, b) => getRankInNum(b) - getRankInNum(a));

console.log(res);

Upvotes: 0

Related Questions