1

if have such a condition

var list = {
  "you": 100, 
  "me": 75, 
  "foo": 116, 
  "bar": 15
};

can i sort this object on the basis of array of keys in like:-

[
"me",
"bar",
"you",
"foo"
]

Answer should look like:

list = {
  "me": 75, 
  "bar": 15,
  "you": 100, 
  "foo": 116
};
rvandoni
  • 3,130
  • 3
  • 29
  • 43
Vishal Gupta
  • 211
  • 1
  • 8
  • 7
    Objects do not have a set order. It's not possible to sort them. – Calvin Godfrey Jan 16 '19 at 15:18
  • On what basis are you trying to sort it? – Avanthika Jan 16 '19 at 15:23
  • 1
    You can have this behavior doing `let result = {}; [ 'me', 'bar', 'you', 'foo' ].forEach(key => result[key] = list[key])` (creating another object in a specific order), but it does not make sense, as @CalvinGodfrey pointed out, an object does not have any set order. – Cinn Jan 16 '19 at 15:26

1 Answers1

0

you can do something like this

const orderedList = Object.keys(list).sort((a, b) => list[a] - list[b]);

but you will have an array, because an object cannot have an order and is not possibile to sort its attributes.

rvandoni
  • 3,130
  • 3
  • 29
  • 43
  • 1
    op has already a sorted array of keys. – Nina Scholz Jan 16 '19 at 15:24
  • I think this is a reasonable answer, but I'd suggest reformatting it to first discuss how object properties don't have order and then suggest the array method, if an array is suitable. – Nick Jan 16 '19 at 15:29
  • If i can sort an object on the basis of its keys, then don't you think i can also sort the object on the basis of the array of its key? Do you my question is incorrect? @NinaScholz – Vishal Gupta Jan 16 '19 at 15:42
  • @VishalGupta, it's your question, but i mean if you already have an array of sorted keys, you do not need to sort this array. so it's more a questn, why you want a sorted object (which is possible under some preconditions). – Nina Scholz Jan 16 '19 at 15:47