I am trying to sort this array:
[
{
"id": 877234004,
"name": "app.js",
"type": "FILE",
"parentId": 877234003
},
{
"id": 877234010,
"name": "project",
"type": "DIRECTORY"
},
{
"id": 877234002,
"name": "src",
"type": "DIRECTORY",
"parentId": 877234010
},
{
"id": 877234003,
"name": "app",
"type": "DIRECTORY",
"parentId": 877234002
}
]
As you can see, there are object who doesn't have parentId. I need to keep this one on the top and the rest will be sorted by id.
Here's my code:
input.sort(function (a, b) {
if (typeof a.parentId === 'undefined'))
return -1;
else
return a.id - b.id;
});
It doesn't work though. Is it possible to do this?
Expected result:
[
{
"id": 877234010,
"name": "project",
"type": "DIRECTORY"
},
{
"id": 877234002,
"name": "src",
"type": "DIRECTORY",
"parentId": 877234010
},
{
"id": 877234003,
"name": "app",
"type": "DIRECTORY",
"parentId": 877234002
},
{
"id": 877234004,
"name": "app.js",
"type": "FILE",
"parentId": 877234003
}
]
Thanks in advance
parentId877234003 will come first thenparentId877234003. pls edit your question.