Skip to content

Instantly share code, notes, and snippets.

@ecarter
Created December 2, 2011 15:40
Show Gist options
  • Select an option

  • Save ecarter/1423674 to your computer and use it in GitHub Desktop.

Select an option

Save ecarter/1423674 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));
@prakashmallow
Copy link
Copy Markdown

Finally I got what I was looking for. Thanks @kkoo95

@sujinleeme
Copy link
Copy Markdown

sujinleeme commented Mar 20, 2023

Here is the code If you want to move unmated rest of items at the end of array.

export const mapOrder = <T>(array: T[], order: any[], key: keyof T) => {
  return array.sort((a, b) => {
    let weightA = 0;
    let weightB = 0;

    if (!order.includes(a[key])) {
      weightA += 100;
    }

    if (!order.includes(b[key])) {
      weightB += 100;
    }

    return order.indexOf(a[key]) + weightA - (order.indexOf(b[key]) + weightB);
  });
};

Test Case

 const item_array = [
    { id: 2, label: "Two" },
    { id: 3, label: "Three" },
    { id: 5, label: "Five" },
    { id: 4, label: "Four" },
    { id: 1, label: "One" }
  ];

  const item_order = [1, 5];

  const ordered_array = mapOrder(item_array, item_order, "id");
  
console.log("Ordered:", JSON.stringify(ordered_array));
// Ordered: [{"id":1,"label":"One"},{"id":5,"label":"Five"},{"id":2,"label":"Two"},{"id":3,"label":"Three"},{"id":4,"label":"Four"}] 

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment