Sorting One Array With Another in JavaScript

March 13, 2022

Recently I needed to sort one array I had no control of to show specific categories in a specific order. Any items in the array of categories that I had not specified in my order array I needed to go at the end of my list. No other order mattered.

I solved this with a simple JS sort function with a little extra code for handling items not in the list.

const categoriesArray = [
  { category: 'stuff' },
  { category: 'things' },
  { category: 'unknown' },
  { category: 'important' },
];
const order = ['important', 'things', 'stuff'];

const sortedArray = categoriesArray
  .slice()
  .sort(({ category: categoryA }, { category: categoryB }) => {
    const indexA = order.indexOf(categoryA);
    const indexB = order.indexOf(categoryB);
    return (
      (indexA > -1 ? indexA : Infinity) - (indexB > -1 ? indexB : Infinity)
    );
  });

// Returns:
// ​[
//  { category: "important" },
// ​ { category: "things" },
// ​ { category: "stuff" },
// ​ { category: "unknown" }
// ]

Written by Matt Gregg, a UI engineer who lives and works in Minneapolis, MN

Have something to say about this post? Tweet at me