Clue Mediator

How to sort an array of objects in a specific order in JavaScript

📅February 15, 2022

We were trying to sort an array of objects which contains a status key which has "active", "inactive", "pending". So we just wanted to sort the array in such a way that all "active" records would appear on top followed by "pending" and then "inactive".

Checkout more articles on JavaScript

Let’s consider the following array to sort by `status`.

const arr = [
  { id: "1", name: "Item 1", status: "inactive" },
  { id: "2", name: "Item 2", status: "active" },
  { id: "3", name: "Item 3", status: "inactive" },
  { id: "4", name: "Item 4", status: "active" },
  { id: "5", name: "Item 5", status: "inactive" },
  { id: "6", name: "Item 6", status: "active" },
  { id: "7", name: "Item 7", status: "pending" },
  { id: "8", name: "Item 8", status: "pending" }
];

Now we want to sort an array in the following order.

const statusOrder = ["active", "inactive", "pending"];

Use the following code to sort an array by `statusOrder`.

const result = arr.sort((a, b) => statusOrder.indexOf(a.status) - statusOrder.indexOf(b.status));
console.log(result);
/* Output:
[
  { id: "2", name: "Item 2", status: "active" },
  { id: "4", name: "Item 4", status: "active" },
  { id: "6", name: "Item 6", status: "active" },
  { id: "1", name: "Item 1", status: "inactive" },
  { id: "3", name: "Item 3", status: "inactive" },
  { id: "5", name: "Item 5", status: "inactive" },
  { id: "7", name: "Item 7", status: "pending" },
  { id: "8", name: "Item 8", status: "pending" }
]*/

That’s it for today.
Thank you for reading. Happy Coding..!! 🙂