How to sort array with selected list in javascript?

I have a list look like:

const initArray = [
  {
    id: 0,
  },
  {
    id: 1,
  },
  {
    id: 2,
  },
  {
    id: 3,
  },
];

A selected list look like:

const selectedList = [
  {
    id: 2,
  },
];

And the desired data has been sorted:

const outPut= [
  {
    id: 2,
  },
  {
    id: 0,
  },
  {
    id: 1,
  },
  {
    id: 3,
  },
];

I’m in trouble right now, so I can’t figure it out yet.

Can you share some solutions?

>Solution :

You could take an object which keeps the order of the first objects and sort the rest after.

const
    data = [{ id: 0 }, { id: 1 }, { id: 2 }, { id: 3 }],
    selectedList = [{ id: 2 }],
    order = Object.fromEntries(selectedList.map(({ id }, i) => [id, i + 1]));

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

console.log(data);

Leave a Reply