Skip to content

Instantly share code, notes, and snippets.

@ctwowt
Forked from ecarter/mapOrder.js
Created May 28, 2020 03:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ctwowt/42643ac1bbdd683f90b52fd8ed22eb6f to your computer and use it in GitHub Desktop.
Save ctwowt/42643ac1bbdd683f90b52fd8ed22eb6f 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
*/
function mapOrder (array, order, key) {
array.sort( function (a, b) {
var A = a[key], B = b[key];
if (order.indexOf(A) > order.indexOf(B)) {
return 1;
} else {
return -1;
}
});
return array;
};
/**
* Example:
*/
var item_array, item_order, ordered_array;
item_array = [
{ id: 2, label: 'Two' }
, { id: 3, label: 'Three' }
, { id: 5, label: 'Five' }
, { id: 4, label: 'Four' }
, { id: 1, label: 'One'}
];
item_order = [1,2,3,4,5];
ordered_array = mapOrder(item_array, item_order, 'id');
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