Skip to content

Instantly share code, notes, and snippets.

@PaulSanchez12
Created May 23, 2020 01:18
Show Gist options
  • Save PaulSanchez12/615ccff662e0dc435a28a7c859c564c4 to your computer and use it in GitHub Desktop.
Save PaulSanchez12/615ccff662e0dc435a28a7c859c564c4 to your computer and use it in GitHub Desktop.
Order an array of objects based on another array order
/**
* Sort array of objects based on another array
*/
const mapOrder = (array: any, order: any, key: any) => {
array.sort((a: any, b: any) => {
const A = a[key];
const B = b[key];
return order.indexOf(A) > order.indexOf(B) ? 1 : -1;
});
return array;
};
/**
* Example:
*/
var item_array, item_order, ordered_array, item_order_2, item_order_3;
item_array = [
{ id: 2, label: 'Two', se: { new: false } }
, { id: 3, label: 'Three', se: { new: false } }
, { id: 5, label: 'Five', se: { new: false } }
, { id: 4, label: 'Four', se: { new: false } }
, { id: 1, label: 'One', se: { new: true } }
];
item_order = [1, 2, 3, 4, 5];
item_order_2 = ['Five', 'Four', 'Three', 'Two', 'One'];
item_order_3 = [true, false];
ordered_array = mapOrder(item_array, item_order_2, 'label');
console.log('Ordered:', JSON.stringify(ordered_array));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment