Last active
October 4, 2017 14:02
-
-
Save krstffr/ff6fd22cd235295459be13e37cf58d9c to your computer and use it in GitHub Desktop.
Sorting an array based on another array (JS)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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. | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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