'Sort date property in object in ascending order Angularjs/Javascript
When I console.log the details
variable, I get the following results:
details:{
1:{
2015-2-10 : 0
2015-2-11 : 0
2015-2-12 : 0
2015-2-13 : 0
2015-2-14 : 0
2015-2-15 : 0
2015-2-16 : 0
2015-2-17 : 0
2015-2-18 : 0
2015-2-19 : 0
2015-2-2 : 0
2015-2-20 : 0
2015-2-21 : 0
2015-2-22 : 0
2015-2-23 : 0
2015-2-24 : 0
2015-2-25 : 0
2015-2-26 : 0
2015-2-27 : 1
2015-2-28 : 1
2015-2-3 : 0
2015-2-4 : 0
2015-2-5 : 0
2015-2-6 : 0
2015-2-7 : 0
2015-2-8 : 0
2015-2-9 : 0
2015-3-1 : 0
}
}
I want to do is to display the dates with ascending order. So the output will become:
details:{
1:{
2015-2-2 : 0
2015-2-3 : 0
2015-2-4 : 0
2015-2-5 : 0
2015-2-6 : 0
2015-2-7 : 0
2015-2-8 : 0
2015-2-9 : 0
2015-2-10 : 0
2015-2-11 : 0
2015-2-12 : 0
2015-2-13 : 0
2015-2-14 : 0
2015-2-15 : 0
2015-2-16 : 0
2015-2-17 : 0
2015-2-18 : 0
2015-2-19 : 0
2015-2-20 : 0
2015-2-21 : 0
2015-2-22 : 0
2015-2-23 : 0
2015-2-24 : 0
2015-2-25 : 0
2015-2-26 : 0
2015-2-27 : 1
2015-2-28 : 1
2015-3-1 : 0
}
}
My question: Is it possible to do it?
my plunker is http://plnkr.co/edit/dQO3D1Omc0o7ZH9TfeUZ?p=preview Thanks in advance!
Solution 1:[1]
My question: Is it possible to do it?
As of ES2015, yes, it's possible, but it's almost always a bad idea. When you want a specific order, use an array or (in some limited situations) a Map
(Map
objects are ordered strictly by when an entry for a key was first added).
The reason it's possible with your specific example is that those properties are all "own" properties (not inherited) and their names are not integer indexes. For that subset of properties, the order is the order the property was adding to the object. So to do what you describe, you'd create a new object, and add the properties to it in the order you want them to appear.
But again: Don't do that. :-) Use an array of name
/value
objects, or a Map
.
As of ES5 (when this question was first asked): No. The structure you've quoted is an object with property names like "2015-02-28"
. Objects in JavaScript have no order to their properties at all. To have order, you must (for now) have an array. ES6 will introduce Map
objects, which are maps ordered by the insertion order of their keys. But ES5 doesn't have those.
That doesn't mean you can't access those properties in any order you want. You can get an array of the property names via Object.keys
, and you can sort arrays however you like.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |