0

I have an object containing objects with objects within them. Each object have an ordernum. I want to sort the objects with the lowest ordernum first.

I have used the function bellow when sorting arrays but I need help adjusting it to this structure.

function(a, b) {
return parseFloat(a.ordernum) - parseFloat(b.ordernum);
}

Ann
  • 49
  • 3
  • 6
    Objects do not have order so not sure how you are going to sort them. – epascarello Oct 20 '17 at 15:36
  • I had just visited [this question](https://stackoverflow.com/questions/46849294/sorting-associative-array-of-objects-in-javascript#comment80646393_46849294) not too long ago... why does everyone want to sort objects today? While it is possible to sort properties with some restrictions, one should not do it. – ASDFGerte Oct 20 '17 at 15:38
  • Consider using lodash. You can use `var obj = _.mapKeys(objects, (o) => o.sortField);` and then use `_.sortBy(obj, (o) => o.sortField)` **AND** if needed, `_.reverse(obj)` – fungusanthrax Oct 20 '17 at 15:39
  • Possible duplicate of [Sorting JavaScript Object by property value](https://stackoverflow.com/questions/1069666/sorting-javascript-object-by-property-value) – Nick is tired Oct 20 '17 at 15:56
  • Take a look at this answer about ordering in objects: [Does JavaScript guarantee object property order](https://stackoverflow.com/questions/5525795/does-javascript-guarantee-object-property-order) – rymdmaskin Oct 20 '17 at 16:00

1 Answers1

0

Maybe sort + convert to an array then ?:

const result =
 Object.values( yourobject )
  .sort((a,b)=> a.ordernum - b.ordernum );
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151