user3401734
user3401734

Reputation: 13

How to Sort the JSON array in the controller of AngularJS?

Kindly help me in sorting the below JSON list in the controller and display in the view.

Actually orderBy filter sorting one level, But I need it sort even for childs recursively.

Input:

R2
-->S4
------>T5
------>T4
-->S3
R1
-->S2
------>T2
------>T1
-->S1

Output:

R1
-->S1
------>T1
------>T2
-->S2
R2
-->S3
------>T4
------>T5
-->S4

Please find the sample in Plunker.

http://plnkr.co/edit/JslHwJ1CBREKf6FgYHaZ?p=preview

Upvotes: 1

Views: 2285

Answers (1)

adrichman
adrichman

Reputation: 1235

var sortNames = function(arr){

  arr = arr.sort(function(a,b){
    return a.name > b.name;
  })

  for (var i = 0; i < arr.length; i++){
    if (arr[i].childs){
      sortNames(arr[i].childs)
    }
  }
  return arr;
}
var names = [
    {
        "name": "Root1",
        "Id": "2f3d17cb-d9e2-4e99-882d-546767f2765d",
        "status": "",
        "dispName": "",
        "imageURL": "",
        "childCount": "",
        "childs": [
            {
                "name": "Sub1",
                "Id": "ff8b3896-3b80-4e1b-be89-52a82ec9f98f",
                "childs": [
                    {
                        "name": "Template1",
                        "Id": "ff8b3896-3b80-4e1b-be89-52a82ec9f981",
                        "status": "",
                        "dispName": "",
                        "imageURL": ""
                    },
                    {
                        "name": "Template2",
                        "Id": "ff8b3896-3b80-4e1b-be89-52a82ec9f982",
                        "status": "",
                        "dispName": "",
                        "imageURL": ""
                    }
                ]
            },
            {
                "name": "Template3",
                "Id": "ff8b3896-3b80-4e1b-be89-52a82ec9f981"

            }
        ]
    },
    {
        "name": "Root2",
        "Id": "ea0586e7-02cf-4359-94ba-8d9623590dfe",
        "childs": [
            {
                "name": "Sub2",
                "Id": "6f1b3a60-d295-413e-92ef-1c713446e6c9",
                "childs": [
                    {
                        "name": "Template4",
                        "Id": "6f1b3a60-d295-413e-92ef-1c713446e6c1"
                    },
                    {
                        "name": "Template5",
                        "Id": "6f1b3a60-d295-413e-92ef-1c713446e6c2"
                    }
                ]
            }
        ]
    }
];

sortNames(names);

Upvotes: 1

Related Questions