0

How can I sort an array of objects that looks like that:

 data = [{'Name': 'Peter', 'Chemistry': 10, 'Math': 9, 'Geography': 5},
         {'Name': 'Bob', 'Math': 6, 'Chemistry': 10, 'Geography': 5}]

by course name only. Hence, it will look like

 data = [{'Name': 'Peter', 'Chemistry': 10, 'Geography': 5, 'Math': 9,},
         {'Name': 'Bob', 'Chemistry': 10, 'Geography': 5, 'Math': 6, }]
Marten
  • 1,376
  • 5
  • 28
  • 49
Aenaon
  • 3,169
  • 4
  • 32
  • 60
  • 3
    You can't sort the keys of an object. – Andy Apr 15 '19 at 12:42
  • No you can't sort them, you can only sort by `alphabetic ( A to Z )` or ascending order you can [read this](https://www.stefanjudis.com/today-i-learned/property-order-is-predictable-in-javascript-objects-since-es2015/) – Code Maniac Apr 15 '19 at 12:42
  • There is not guarantee of keys object. – Maheer Ali Apr 15 '19 at 12:42
  • to be able to change keys order use `Map` instead of object – lankovova Apr 15 '19 at 12:44
  • An object is a member of the type Object. It is an _unordered_ collection of properties each of which contains a primitive value, object, or function. – Walk Apr 15 '19 at 12:44
  • 3
    Although [properties do have order now](https://stackoverflow.com/questions/30076219/does-es6-introduce-a-well-defined-order-of-enumeration-for-object-properties), *using* that order is almost never what you want. (@Andy) – T.J. Crowder Apr 15 '19 at 12:46
  • 1
    @Walk - Not anymore (see above; not that using the order is a good idea). :-) – T.J. Crowder Apr 15 '19 at 12:47
  • @Aenaon Go through this how you can use `Map();` https://stackoverflow.com/questions/37056250/how-can-we-custom-sort-javascript-object-keys – Mehraj Khan Apr 15 '19 at 12:49
  • um can I know why u need to sort them because you can just change your logic like for eg( console.log(obj.name,obj.chemistry,obj.geography, obj.math) ), in the order you want – akshay kishore Apr 15 '19 at 12:49
  • Guys, I dont think it is a duplicate, as you sort some of the keys and the rest are left untouched. Thanks anyway for the replies – Aenaon Apr 15 '19 at 12:51

0 Answers0