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 and 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" }
// ]
Top comments (0)