Home > front end >  How to sort array with selected list in javascript?
How to sort array with selected list in javascript?

Time:11-23

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?

CodePudding user response:

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);

CodePudding user response:

const _sort = (arr = [], selected = []) => {
  const priority = new Set( selected.map(({ id }) => id) );
  return [...arr].sort(({ id: a }, { id: b }) => priority.has(b) - priority.has(a));
}

const 
  initArray = [ { id: 0 }, { id: 1 }, { id: 2 }, { id: 3 } ],
  selectedList = [ { id: 2 } ];
console.log( _sort(initArray, selectedList) );

  • Related