Skip to content

Instantly share code, notes, and snippets.

@krstffr
Last active October 4, 2017 14:02
Show Gist options
  • Save krstffr/ff6fd22cd235295459be13e37cf58d9c to your computer and use it in GitHub Desktop.
Save krstffr/ff6fd22cd235295459be13e37cf58d9c to your computer and use it in GitHub Desktop.
Sorting an array based on another array (JS)
// We have this array of people, we want to get a new array sorted using the names in the order array below.
const collection = [{ name: 'carol' }, { name: 'stewie' }, { name: 'steve' }, { name: 'carl' }];
const order = ['carl', 'steve', 'carol', 'horseboy', 'stewie'];
// Just map over the order, and find the corresponding item in the collection.
const sortedCollection = order.map(orderName => collection.find(({ name }) => name === orderName ));
// To also remove undefindes, if the order element isn't found in the collection,
// do this (filter out any falsy elements)
sortedCollection.filter(x => x);
/*
Notes on performance: The .find() function is probably O(N), which means that if you have a large collection
and you run this sort thing often (very often) you should consider optimzing it.
*/
@krstffr
Copy link
Author

krstffr commented Mar 23, 2017

Note: if the element is not in the order-array, it will return an undefined item at that location. So there are improvements to be made!

EDIT: Fixed with the filter-example

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment