Table of contents
#ES6: Sort an array based on another array
Last updatedOriginally published#Array of Numbers
This is more to show the basic idea
JavaScript
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 😉
JavaScript
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.
JavaScript
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.
#Related reads
Share