afewminutesofcode.com

How to create a custom sort order in javascript

Cover Image for How to create a custom sort order in javascript

When sorting an array of objects in JavaScript, usually we will want to sort alphabetically or numerically, but there are also some cases were we might need a custom sort order.

Take the below example we want to show the items inProgress first, then todo and then done.

const tasks = [
  { id: 1, title: "Job A", status: "done" },
  { id: 2, title: "Job B", status: "inProgress" },
  { id: 3, title: "Job C", status: "todo" },
  { id: 4, title: "Job D", status: "inProgress" },
  { id: 5, title: "Job E", status: "todo" },
];

We will first create an array with our desired sort order.

const sortBy = ["inProgress", "todo", "done"];

Then we will make a function using reduce that will output the data as an object. {inProgress: 0, todo: 1, done: 2} with the array item as the key and the index as the value.

const sortByObject = (data) =>
  data.reduce((obj, item, index) => {
    return {
      ...obj,
      [item]: index,
    };
  }, {});
console.log(sortByObject(sortBy));
/* {inProgress: 0, todo: 1, done: 2} */

Now we have our sorting setup we can bring it all together with a reusable function that passes in an array data a sortby array and a sortField so we know whoch field to sort on.

const customSort = ({ data, sortBy, sortField }) => {
  const sortByObject = sortBy.reduce((obj, item, index) => {
    return {
      ...obj,
      [item]: index,
    };
  }, {});
  return data.sort(
    (a, b) => sortByObject[a[sortField]] - sortByObject[b[sortField]]
  );
};

console.log(customSort({ data: tasks, sortBy, sortField: "status" }));

This will now sort by our custom order, however there will be an issue if there is an item in the list that has a different status (one not in our sort order). So to handle this we will set a default sort field to catch all items we don't want in the sort.

const tasksWithDefault = tasks.map((item) => ({
  ...item,
  sortStatus: sortBy.includes(item.status) ? item.status : "other",
}));

With this in place if we log out our function again this time passing in our updated sort field then we now have our correct sort order with other items at the bottom of the list.

console.log(
  customSort({
    data: tasksWithDefault,
    sortBy: [...sortBy, "other"],
    sortField: "sortStatus",
  })
);

You might also like

Cover Image for Check if a string contains a substring in JavaScript

Check if a string contains a substring in JavaScript

Since ES6 you can now use the built in includes method eg string.includes(substring).

Cover Image for Create a Cricket Points Table in Javascript - Part 5

Create a Cricket Points Table in Javascript - Part 5

In this tutorial we are going to build our points table based off our previous work.

Cover Image for Create a Cricket Points Table in Javascript - Part 4

Create a Cricket Points Table in Javascript - Part 4

In this tutorial we are going to complete the rest of the calculations required for the points table.

Cover Image for Create a Cricket Points Table in Javascript - Part 3

Create a Cricket Points Table in Javascript - Part 3

In this tutorial we are going to create functions to calculate the total number of wins, losses, no results and points a team has for the tournament.

Cover Image for Create a Cricket Points Table in Javascript - Part 2

Create a Cricket Points Table in Javascript - Part 2

In this tutorial we are going to create a function to calculate when a team has won, lost or there is no result.

Cover Image for Create a Cricket Points Table in Javascript - Part 1

Create a Cricket Points Table in Javascript - Part 1

In this tutorial we are going to Create a Cricket Points Table in JavaScript.

Cover Image for Create a weather voice assistant in React

Create a weather voice assistant in React

In this tutorial we are going to create a simple React app that will use the speechSynthesis API to speak the current temperature in the city we type in.

Cover Image for Getting to know the many voices in your browser

Getting to know the many voices in your browser

The Speech Synthesis API has been around since about 2014 but still has not gained a huge amount of traction on many sites.

Cover Image for How to create a custom sort order in javascript

How to create a custom sort order in javascript

When sorting an array of objects in JavaScript, usually we will want to sort alphabetically or numerically, but there are also some cases were we might need a custom sort order.

Cover Image for How to sort an array alphabetically in javascript

How to sort an array alphabetically in javascript

To sort an array alphabetically in javascript you can use the sort function.

Cover Image for How to sort an array numerically in javascript

How to sort an array numerically in javascript

To sort an array in javascript use the sort method sort((a, b) => a - b)

Cover Image for How to convert an array into an object in javascript

How to convert an array into an object in javascript

To convert an array into an object we will create a function and give it 2 properties, an array and a key..

Cover Image for How to filter an array in javascript

How to filter an array in javascript

To filter an array in Javascript we can pass in a condition to the built in filter function.