-1

I have an array of objects that I want sorted in an unconventional way.

[
  {
    type: 'web',
    id: 1
  },
  {
    type: 'graphics',
    id: 2
  },
  {
    type: 'UX',
    id: 3
  },
  {
    type: 'custom',
    id: 4
  }
]

How would I go about sorting this array by object.id so they appear in the order 1, 3, 4, 2 instead?

3
  • @falinsky: that answers a different question, but this question has definitely been asked before. Let me look. Commented Nov 19, 2020 at 14:28
  • @ScottSauyet I apologize if that's the case, I was trying to look through similar questions but couldn't find the correct search term for it i guess. Commented Nov 19, 2020 at 16:46
  • @Oliver: It's not a big deal. We close as duplicates so that there can be definitive answers to common questions, but it took me a bit of searching to find a correct duplicate, too. Please let us know if neither one is a reasonable answer to your question. Commented Nov 19, 2020 at 17:14

2 Answers 2

1

You could use an order array for achieving this.

Creating a dictionary is more efficient than using indexOf method because the lookup for the dictionary is O(1).

var array = [ { type: 'web', id: 1 }, { type: 'graphics', id: 2 }, { type: 'UX', id: 3 }, { type: 'custom', id: 4 } ];

var order = [1, 3, 4, 2];
var orderDict =  order.reduce((acc, item, index) => {
  acc[item] = index;
  return acc;
}, {});

array.sort((a, b) => orderDict[a.id] - orderDict[b.id]);
console.log(array);

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

6 Comments

Yes, a dictionary will be more efficient... eventually. But the size of the data is important too. I'd be surprised if the costs of creating the dictionary are outweighed by the O(n) lookup in an array for a few entries or even a few dozen. Be wary of premature optimizations.
@ScottSauyet, yes, creating dictionary is O(n) but indexOf has complexity O(n) because is unsorted array and it's executed many times while sort is executing.
But do you think that for the example of four items this would be more faster than the simpler indexOf answer?
For this small case, indexOf is faster. (jsbench.me/o4khoxzxiz/1) I don't know where the break-even point would be.
Yes, that's all I was saying. You can see in one of the duplicates that I was suggesting your approach, but if this case is as small as suggested, I would suggest the simpler code.
|
0

sort in javascript can use original function.

arr=[
    {
      type: 'web',
      id: 1
    },
    {
      type: 'graphics',
      id: 2
    },
    {
      type: 'UX',
      id: 3
    },
    {
      type: 'custom',
      id: 4
    }
  ]

sort_key=[1,3,2,4]

arr.sort((a,b)=>sort_key.indexOf(a.id)-sort_key.indexOf(b.id))

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.