2

I have a JSON, as seen below, and I want to sort this JSON data with rowNo and columnNo.

How can I do this?

jsonArrayFull: {
    Dashboard: [{
        "id": "three-col-layout-div1",
        "rowNo": "1",
        "columnNo": "0",
        "colspan": "1",
        "rowspan": "1",
        "title": "Harvester Productivity Analysis",
        "dashlet": "MIS/MISViewer/HarvesterProductivityAnalysis",
        "bgColor": "#854db0",
        "width": "31.1216429699842%",
        "height": "29.985007496251875%"
    }, {
        "id": "three-col-layout-div2",
        "rowNo": "1",
        "columnNo": "1",
        "colspan": "1",
        "rowspan": "1",
        "title": "Expense Analysis",
        "dashlet": "MIS/MISViewer/ExpenditureAnalysis",
        "bgColor": "#83a143",
        "width": "31.1216429699842%",
        "height": "29.985007496251875%"
    }, {
        "id": "three-col-layout-div3",
        "rowNo": "1",
        "columnNo": "2",
        "colspan": "1",
        "rowspan": "1",
        "title": "Labour Utilization",
        "dashlet": "MIS/MISViewer/LabourUtilization",
        "bgColor": "#a32a2a",
        "width": "31.1216429699842%",
        "height": "29.985007496251875%"
    }]
}

I did this script but its not working

for(var i=0;i<newDiv.length;i++) {
    newDiv[i].dashlets.sort(function(obj1, obj2) {
        return obj1.rowNo - obj2.rowNo;
    });
}
GillesC
  • 10,647
  • 3
  • 40
  • 55
Nithin Viswanathan
  • 3,245
  • 7
  • 39
  • 84

2 Answers2

0

Your JSON defines the Dashboard property, but the code you've provided works with dashlets.

Try out this one:

for(var i = 0; i < newDiv.length; i++)
{
    newDiv[i].Dashboard.sort(function(obj1, obj2) {
        return obj1.rowNo - obj2.rowNo;
    });
}

Update:
If you want to sort the array by two keys, please, refer this one answer:

How to sort an array of objects by multiple fields?

You should add some logic into your function, it can't be done in a one stroke.

Community
  • 1
  • 1
VMAtm
  • 27,943
  • 17
  • 79
  • 125
0

To sort an array of object using two keys, you could do

Dashboard.sort(function(o1,o2){ if( o1.rowNo == o2.rowNo ) { return o1.columnNo - o2.columnNo } return o1.rowNo - o2.rowNo });

This one sorts first by rowNo, and then by columnNo.

Rliger
  • 79
  • 4