I'm learning TypeScript and JS and struggling to solve multiple problems. One of them is this, that I have at hand. Say, I have an array of Application objects. Each Application object has this kind of a nested structure:
Application
|
----[Document Type]
---------|
--------------[Document]
------------------|
------------------------Metadata
(Each Application has an array of Document Type.
Each Document Type has an array of Document.
Each Document has a Metadata inside it)
All the three objects types -- Application, Document Type, Document...have a property called name inside them.
I want to sort the entire array of Application objects (and recursively the nested objects as well), based on ascending order of the name property of each object. I had been trying multiple examples, but those are all sorting only the root level objects (Application) and not the nested objects.
Here is one such example I tried:
var simplePropertyRetriever = function(obj:any) {
return obj.name;
};
function sortArrayByName(propertyRetriever, arr:Application[]) {
arr.sort(function (a, b) {
var valueA = propertyRetriever(a);
var valueB = propertyRetriever(b);
if (valueA < valueB) {
return -1;
} else if (valueA > valueB) {
return 1;
} else {
return 0;
}
});
};
Can anybody please advise how to do this?
My sample JSON is this (I have arranged the objects in descending order here, to better explain my use case):
[
{
"name": "Application 2",
"children": [
{
"name": "Operations Manual",
"children": [
{
"name": "2nd-opsManual-app1",
"metadata": {
"size": 56,
"fileExtension": "docx"
}
},
{
"name": "1st-opsManual-app1",
"metadata": {
"size": 56,
"fileExtension": "pdf"
}
}
]
},
{
"name": "Interface Contracts",
"children": [
{
"name": "2nd-IntContracts-app1",
"metadata": {
"size": 56,
"fileExtension": "docx"
}
},
{
"name": "1st-IntContracts-app1",
"metadata": {
"size": 56,
"fileExtension": "pdf"
}
}
]
}
]
},
{
"name": "Application 2",
"children": [
{
"name": "User Manual",
"children": [
{
"name": "2nd-userManual-app2",
"metadata": {
"size": 56,
"fileExtension": "docx"
}
},
{
"name": "1st-userManual-app2",
"metadata": {
"size": 56,
"fileExtension": "pdf"
}
}
]
},
{
"name": "System Design",
"children": [
{
"name": "2nd-SystemDesign-app2",
"metadata": {
"size": 56,
"fileExtension": "docx"
}
},
{
"name": "1st-SystemDesign-app2",
"metadata": {
"size": 56,
"fileExtension": "pdf"
}
}
]
}
]
}
]