0

I have two arrays:

Original Array:

[{id:1, name:'A'},{id:2, name:'B'},{id:3, name:'C'},{id:4, name:'D'},{id:5, name:'E'}]

There is one more array:

New Array:

[{id:3, name:'C'},{id:5, name:'E'},{id:2, name:'B'}]

I want the new array to be sorted based on the id of the original array, so that the resolt is as follows:

Sorted New Array

[{id:2, name:'B'},{id:3, name:'C'},{id:5, name:'E'}]

Can you please guide me on how how can do this sorting?I just don't know where to start?

asanas
  • 3,782
  • 11
  • 43
  • 72
  • Does this answer your question? [Sort array of objects by string property value](https://stackoverflow.com/questions/1129216/sort-array-of-objects-by-string-property-value) – evolutionxbox Jan 19 '21 at 13:24
  • No it doesn't help because in that question the sorting is based on the key within the same array. – asanas Jan 19 '21 at 13:25

2 Answers2

0

You could take an object for the wanted order and sort by the delty of the original order.

This approach allows to sort unknown id to a wanted position as well. If so take

  • n for any position inside of the array,
  • -Number.MAX_VALUE for top position or
  • Number.MAX_VALUE for sorting to the end.

Then you need the following callback:

(order[a.id] || position) - (order[b.id] || position)

const
    original = [{ id: 1, name: 'A' }, { id: 2, name: 'B' }, { id: 3, name: 'C' }, { id: 4, name: 'D' }, { id: 5, name: 'E' }],
    data = [{ id: 3, name: 'C' }, { id: 5, name: 'E' }, { id: 2, name: 'B' }],
    order = Object.fromEntries(original.map(({ id }, i) => [id, i + 1]));

data.sort((a, b) => order[a.id] - order[b.id]);

console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

Using Array.reduce to sort the data.

const arr1 = [{id:1, name:'A'},{id:2, name:'B'},{id:3, name:'C'},{id:4, name:'D'},{id:5, name:'E'}];

const arr2 = [{id:3, name:'C'},{id:5, name:'E'},{id:2, name:'B'}];

const sortedArray2 = arr1.reduce((tmp, x) => {
  const elem = arr2.find(y => y.id === x.id);
  
  return elem ? [
    ...tmp,
    elem,
  ] : tmp;
}, []);

console.log(sortedArray2);
Orelsanpls
  • 22,456
  • 6
  • 42
  • 69