Sorting an array of objects by an array JavaScript


Suppose, we have an array of objects and an array of strings like this −

Example

const orders = [
   { status: "pending"},
   { status: "received" },
   { status: "sent" },
   { status: "pending" }
];
const statuses = ["pending", "sent", "received"];

We are required to write a JavaScript function that takes in two such arrays. The purpose of the function should be to sort the orders array according to the elements of the statuses array.

Therefore, objects in the first array should be arranged according to the strings in the second array.

Example

const orders = [
   { status: "pending" },
   { status: "received" },
   { status: "sent" },
   { status: "pending" }
];
const statuses = ["pending", "sent", "received"];
const sortByRef = (orders, statuses) => {
   const sorter = (a, b) => {
      return statuses.indexOf(a.status) - statuses.indexOf(b.status);
   };
   orders.sort(sorter);
};
sortByRef(orders, statuses); console.log(orders);

Output

And the output in the console will be −

[
   { status: 'pending' },
   { status: 'pending' },
   { status: 'sent' },
   { status: 'received' }
]

Updated on: 23-Nov-2020

485 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements