5

I have to sort my array of objects based on their status property

for example, I have the following array

[
{userName:"One", status:"Live"},
{userName:"Two", status:"Rejected"},
{userName:"Three", status:"To Do"},
{userName:"Four", status:"Verify"},
{userName:"Five", status:"Received"},
{userName:"Six", status:"In Progress"}
]

after sorting, I need an array that looks like

[
{userName:"Three", status:"To Do"},
{userName:"Five", status:"Received"},
{userName:"Six", status:"In Progress"},
{userName:"Two", status:"Rejected"},
{userName:"Four", status:"Verify"},
{userName:"One", status:"Live"}
]

Need to sort the items based on its status property in following order

  1. To Do
  2. Received
  3. In Progress
  4. Rejected
  5. Verify
  6. Live

There can be more than one item with same status.

Gholamali Irani
  • 4,391
  • 6
  • 28
  • 59
ebin
  • 191
  • 2
  • 5

1 Answers1

18

You can define an array of status in order, and then use the status' index to sort the array.

let status = {
  'To Do': 1,
  'Received': 2,
  'In Progress': 3,
  'Rejected': 4,
  'Verify': 5,
  'Live': 6
};

let data = [{
    userName: "One",
    status: "Live"
  },
  {
    userName: "Two",
    status: "Rejected"
  },
  {
    userName: "Three",
    status: "To Do"
  },
  {
    userName: "Four",
    status: "Verify"
  },
  {
    userName: "Five",
    status: "Received"
  },
  {
    userName: "Six",
    status: "In Progress"
  }
];

data.sort((a, b) => status[a.status] - status[b.status]);
console.log(data);
31piy
  • 23,323
  • 6
  • 47
  • 67
  • `var status = [ ... ].reduce((o, k, i) => Object.assign(o, {[k]: i}), {})` and `data.sort((a, b) => status[a.status] - status[b.status])` changes O(N) `indexOf()` to O(1) property access. – Patrick Roberts Dec 19 '17 at 10:57
  • @PatrickRoberts -- was working on it. But I don't know why it doesn't work in SO's snippet, but works perfectly fine in [JSFiddle](https://jsfiddle.net/o4ut3cnz/). – 31piy Dec 19 '17 at 11:01
  • 3
    There's a global variable `status` in the snippet, change `var` to `let` and it works. This is why ES6 is a thing. Also `data = data.sort(...)` is redundant. the `sort()` method operates in-place, so there's no need for the assignment. – Patrick Roberts Dec 19 '17 at 11:08
  • @PatrickRoberts -- that was the catch! Thanks for pointing it out. – 31piy Dec 19 '17 at 11:18