1

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?

9
  • 2
    If you want to move one item to the front of the array, you first need to find the index of the item using Array#findIndex; you can use Array#splice to remove that item from the array, and Array#unshift to push it onto the front of the array. Commented Nov 23, 2022 at 9:20
  • does the objects share the same object reference (with same id)? what have you tried? Commented Nov 23, 2022 at 9:23
  • Do you want to sort by the selectedList,then sort by id? Commented Nov 23, 2022 at 9:25
  • thank you so much, especially @BenAston. Commented Nov 23, 2022 at 9:27
  • 1
    If you have big data, and it's sortable, then you will be able to achieve better than O(N) for the algorithm because you will be able to apply a binary chop to exponentially reduce the search space. Commented Nov 23, 2022 at 9:33

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.