0

I have this array:

const list = [{id: 5}, {id: 1}, {id: 4}];

i want to achieve this:

const result = { 5: {id:5}, 1: {id: 1}, 4: {id: 4}};

I tried with reduce, object assign, and it always sorts by id for example:

const listById = list => {
 return list.reduce((acc, cur) => {
  const { id } = cur;
  return {
   ...acc,
   [id]: cur,
 };
}, {});

};

This sorts by id:

{ 1: {id: 1}, 4: {id:4}, 5: {id:5}}

but I don't want that.

neman
  • 196
  • 1
  • 10
  • it is not possible, because index like keys are sorted. you could add a prefix, then the order of insertation matters. – Nina Scholz Feb 06 '20 at 09:07
  • It's not possible. Array indicies are always "sorted" in ascending order when iterated over. – CertainPerformance Feb 06 '20 at 09:07
  • @MihaiAlexandru-Ionut They [are](https://stackoverflow.com/a/58444013) ordered in most situations, but the order is not preserved for array index keys (it's still deterministic, but does not preserve insertion order) – CertainPerformance Feb 06 '20 at 09:08
  • The only real use case I could see where you want the keys of an object ordered is when you are using `Object.entries`,why not try using a `Map` instead? – Kobe Feb 06 '20 at 09:17

0 Answers0