This article has been imported from coding4.gaiama.org and is not necessarily up to date!

ES6: Sort an array based on another array

Last updated: 
Published: 

Table of contents

Array of Numbers

This is more to show the basic idea

const array = [1, 2, 3, 4, 5];
const sortArray = [3, 5, 2, 4, 1];

const arrayMap = array.reduce(
  (accumulator, currentValue) => ({
    ...accumulator,
    [currentValue]: currentValue,
  }),
  {},
);

const result = sortArray.map((key) => arrayMap[key]);
// [3, 5, 2, 4, 1]

Array of Strings

This is actually the same, only changing both inputs. Just to show possibilities 😉

const array = ["jackfruit", "pineapple", "papaya", "watermelon", "banana"];
const sortArray = ["papaya", "banana", "pineapple", "watermelon", "jackfruit"];

const arrayMap = array.reduce(
  (accumulator, currentValue) => ({
    ...accumulator,
    [currentValue]: currentValue,
  }),
  {},
);

const result = sortArray.map((key) => arrayMap[key]);
// ['papaya', 'banana', 'pineapple', 'watermelon', 'jackfruit']

Array of Objects

That's the case I needed it for and am using it to sort the TODO comments on the Roadmap page.

It's almost the same, note how only the key [currentValue.key] differs and has to be present in the array objects.

const array = [
  { key: "banana", value: "A curved yellow fruit" },
  { key: "pineapple", value: "That sour-sweet thing wearing a crown" },
  { key: "durian", value: "The smelly king of fruits" },
];
const sortArray = ["pineapple", "durian", "banana"];

const arrayMap = array.reduce(
  (accumulator, currentValue) => ({
    ...accumulator,
    [currentValue.key]: currentValue,
  }),
  {},
);

const result = sortArray.map((key) => arrayMap[key]);
// [
//   { key: 'pineapple', value: 'That sour-sweet thing wearing a crown' },
//   { key: 'durian', value: 'The smelly king of fruits' },
//   { key: 'banana', value: 'A curved yellow fruit'}
// ]

Here's the relevant code on GitHub Roadmap.js#L48, Roadmap.js#L63-L64 and the nav Roadmap.js#L111

Alternatives

Check out this exhaustive article on StackOverflow showing loads of alternatives 📚 Javascript - sort array based on another array. Theres a similar one using Map.

Can Rau
Can Rau

Doing web-development since around 2000, building my digital garden with a mix of back-to-the-roots-use-the-platform and modern edge-rendered-client-side-magic tech 📻🚀

Living and working in the tropical rainforest of Perú 🐒