Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sorting array manually using a reference array [duplicate]

Tags:

javascript

const order = ['b', 'c', 'a'];

const objects = [
  { name: 'a' },
  { name: 'b' },
  { name: 'c' },
];

Trying to figure out the most efficient way to sort the objects array by name using the manual order array.

like image 570
stewart715 Avatar asked May 11 '26 07:05

stewart715


1 Answers

Here is a quick use of sort plus indexOf.

const order = ['b', 'c', 'a'];

const objects = [
  { name: 'a' },
  { name: 'b' },
  { name: 'c' },
];

const sortedObjects = objects.sort((o1, o2) => order.indexOf(o1.name) - order.indexOf(o2.name));

console.log(sortedObjects);

With cached indices:

const order = ['b', 'c', 'a'].reduce((acc, elt, index) => (acc[elt] = index, acc), {});

const objects = [
  { name: 'a' },
  { name: 'b' },
  { name: 'c' },
];

const sortedObjects = objects.sort((o1, o2) => order[o1.name] - order[o2.name]);

console.log(sortedObjects);
like image 189
sjahan Avatar answered May 13 '26 19:05

sjahan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!