Skip to content

Instantly share code, notes, and snippets.

@kutyel
Last active January 31, 2018 09:17
Show Gist options
  • Save kutyel/4216a61c1cf01325095f7abd7aa5e899 to your computer and use it in GitHub Desktop.
Save kutyel/4216a61c1cf01325095f7abd7aa5e899 to your computer and use it in GitHub Desktop.
Sort an array of objects based on another ordered array of objects 🤓
const copySort = (array, order, key) =>
[...array].sort(
(a, b) => order.findIndex(x => x[key] === a[key]) - order.findIndex(x => x[key] === b[key])
)
const order = [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }, { id: 5 }]
const unordered = [
{ id: 2, label: 'Two' },
{ id: 3, label: 'Three' },
{ id: 5, label: 'Five' },
{ id: 4, label: 'Four' },
{ id: 1, label: 'One' },
]
console.log(copySort(unordered, order, 'id'))
// > [ { id: 1, label: 'One' },
// > { id: 2, label: 'Two' },
// > { id: 3, label: 'Three' },
// > { id: 4, label: 'Four' },
// > { id: 5, label: 'Five' } ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment