Explain Codes LogoExplain Codes Logo

Sort a JavaScript array based on another array

javascript
custom-sorting
advanced-methods
performance
Anton ShumikhinbyAnton Shumikhin·Dec 2, 2024
TLDR
const arr = ['B', 'A', 'C']; const order = ['A', 'B', 'C']; // Sort `arr` to match `order` // It's like rearranging your music playlist according to your mood (or tastes in this case)! const sortedArr = arr.sort((a, b) => order.indexOf(a) - order.indexOf(b));

Custom sorting tricks // or how to level up your sorting wizardry 🧙‍♂️

If the basic solution is not enough for your peculiar needs, don't worry, you're not alone! Let's take a deeper dive into some advanced methods, including object sorting, using external libraries, and improving efficiency.

Sorting complex data with style

If you need to sort objects or prefer a little more flair in your sorting logic, here's a way to use map() and sort() for a custom function:

const itemsArray = [{ id: 'B' }, { id: 'A' }, { id: 'C' }]; const sortingArr = ['A', 'B', 'C']; // Here we are: mapping, spreading and sorting like a pro! const sortedItems = itemsArray .map(item => ({ ...item, sortOrder: sortingArr.indexOf(item.id) })) .sort((a, b) => a.sortOrder - b.sortOrder) .map(item => item.id); // Assuming we're on a mission to only sort 'id's

Call in the cavalry // or when you want to sit back and watch libraries do the work

Sometimes sorting can get a bit messy, and that's the perfect time to bring in the heavy hitters, like Lodash or Underscore.js. They're like your personal Swiss army knife for complex data sorting tasks:

const _ = require('lodash'); // Look ma, I'm sorting with Lodash! const sortedItemsWithLodash = _.sortBy(itemsArray, item => sortingArr.indexOf(item.id));

Outrun the demons of inefficiency // Team O(1) for the win!

If you care about efficiency (and performance), avoid using indexOf within the sort callback as that's like asking each element "Hey, where are you from?" for every comparison. Use a Map for O(1) lookup time, because less is more:

const indexMap = new Map(order.map((item, index) => [item, index])); // Who needs indexOf when you can Map? 💪 const sortedArrBetter = arr.sort( (a, b) => (indexMap.get(a) - indexMap.get(b)) );

Key obstacles and solutions // Because every hero faces challenges

Sorting is not always a walk in the park. Duplicate or missing values can give you a headache. Don't sweat it! Just use array_multisort(), the JavaScript equivalent of PHP, which you can tailor to your needs.

Pragmatic advice // Tried and tested

  • Precompute your sorting order beforehand to fast-track your operations.
  • Sorting objects? Make sure they're compared using a consistent property.
  • Use filtering, mapping and sorting to handle values that can't be compared (null, undefined).
  • And remember, always test your custom sorting logic with sample data!

Adaptation scenarios // One size does not fit all

Different problems need different solving approaches. Here are a few examples:

  • Multidimensional arrays: Need to sort by a value deep down? No problem.
  • Non-standard orderings: Maybe you're sorting numerically but got strings? We've got you covered.
  • Merging sorted arrays: This can save you time but you'll need an efficient comparison method.