0

I have a json file as below.

{
  '003': 'key',
  '001': 'hool',
  '101': 'com',
  '023': 'good'
}

And I want to sort this according to number of key.

{
  '001': 'hool',
  '003': 'key',
  '023': 'good',
  '101': 'com'
}

I made this sort method. But I can modify this to adjust on my case.

  distances.sort((a, b) => {
    return a.num < b.num ? -1 : a.num > b.num ? 1 : 0;
  });

Could you give me an idea for this? Thank you for reading it.

Thomas Jason
  • 378
  • 1
  • 3
  • 13
  • 101 will always be first because of es2015 key traversal order (integer keys are traversed in order). you will have to use a Map() or an array if you need to preserve order – user120242 Jun 18 '20 at 02:41
  • Does this answer your question? [Does ES6 introduce a well-defined order of enumeration for object properties?](https://stackoverflow.com/questions/30076219/does-es6-introduce-a-well-defined-order-of-enumeration-for-object-properties) – user120242 Jun 18 '20 at 02:42
  • Possibly this if he resolves the problem with 101: https://stackoverflow.com/questions/1069666/sorting-object-property-by-values – user120242 Jun 18 '20 at 02:50

1 Answers1

0

You can do this way, using sort() for the Objects keys

let data={
  '003': 'key',
  '001': 'hool',
  '101': 'com',
  '023': 'good'
}
let sortArray = Object.keys(data).sort().map(da=>( { [da] : data[da] } ))
console.log(sortArray)
Narendra Chouhan
  • 2,140
  • 1
  • 9
  • 17