Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading