I am having trouble into sorting the following Object by KEY (DESC). Then, sorting each item by the "notesList.id" property (DESC).
Expected order
- "2017/04/17"
- "2017/03/14"
- "2017/02/30"
Then, for the "2017/04/17" notesList items, here is the Expected order :
- id:57
- id:48
- id:12
The JS Object
var myNotes = {
"customNotes":{
"2017/04/17":{
"concernedDate":"2017/04/17",
"notesList":[
{
"id":48,
"title":"Title 48"
},
{
"id":12,
"title":"Title 12"
},
{
"id":57,
"title":"Title 57"
}
]
},
"2017/02/30":{
"concernedDate":"2017/02/30",
"notesList":[
{
"id":92,
"title":"Title 92"
}
]
},
"2017/03/14":{
"concernedDate":"2017/03/14",
"notesList":[
{
"id":92,
"title":"Title 92"
}
]
}
}
}
The Script
//Convert the OBJECT to an ARRAY
var tmpArr = Object.keys(myNotes.customNotes);
//Sort (Not working)
tmpArr.sort((a, b) => a > b ? a : b);
//Convert back the ARRAY to an OBJECT
Object.keys(myNotes.customNotes).sort((a, b) => a > b ? a : b).map(k => myNotes.customNotes[k]);
What am I missing ? I thank you very much
I observe a few things that seem out of place in your code.
tmpArr.sort((a, b) => a > b ? a : b);
returns a sorted version of tmpArr. it will not modify myNotes object.Object.keys(myNotes.customNotes).sort(...
will return an array of objects from myNotes.customNotes, and not an object that has the same structure as myNotes like you intended.Suppose you want to to get an array, all you need is to fix your sort function and also sort your notesList in the map function. So your code should look like this:
But, if you intend to keep the structure of myNotes, I would suggest that you use reduce function. See my code below:
Your
sort
function should return either zero, a positive number or a negative number. You are just returning the values. Also note that this will convert yourcustomNotes
into an array, since objects cannot be sorted. If you do not wish that to happen, you can maintain another key with a sorted array of the keys incustomNotes
and use this array to look up the values incustomNotes
. Another approach would be to use the newMap
object.Map
supports sorted keys.Try this:
You can use thenBy.js
Like this
You can also sort by property name by using this library
Like this