Lokesh Kumar
Lokesh Kumar

Reputation: 21

How to sort json array having groups of json objects

I want to sort the below json array based on the name attribute. The challenge is if the "rows" contain two json array element then it should first short within the group and then sort based on the other json array.

Here is my attempt. It is sorting the array but not the (elements inside the group)

// sort the data
this.leadPoolRecords = JSON.parse(
  JSON.stringify(this.leadPoolRecords)
).sort((a, b) => {
  a = a[colName] ? a[colName].toLowerCase() : ""; // Handle null values
  b = b[colName] ? b[colName].toLowerCase() : "";
  return a > b ? 1 * isReverse : -1 * isReverse;
});

data =    [
      {
        "button": {
          "btn": true,
          "size": "20"
        },
        "rows": [
          {
            "name": "john",
            "role": "CEO",
            "phone": "xxxxxxxxx",
            "email": "[email protected]"
          }
        ]
      },
      {
        "button": {
          "btn": true,
          "size": "20"
        },
        "rows": [
          {
            "name": "Mike",
            "role": "Director",
            "phone": "xxxxxxxxx",
            "email": "[email protected]"
          }
        ]
      },
      {
        "button": {
          "btn": true,
          "size": "20"
        },
        "rows": [
          {
            "name": "rahul",
            "role": "CTO",
            "phone": "xxxxxxxxx",
            "email": "[email protected]"
          },
          {
            "name": "ajay",
            "role": "Researcher",
            "phone": "xxxxxxxxx",
            "email": "[email protected]"
          }
        ]
      }
    ]

Upvotes: 1

Views: 683

Answers (1)

kol
kol

Reputation: 28728

First, you can sort the rows arrays this way:

data.forEach(item => item.rows.sort((row1, row2) => row1.name.localeCompare(row2.name)));

Then you can sort the elements of data based on the rows arrays. For example, if you want to sort them based on the name of the first row:

data.sort((item1, item2) => item1.rows[0].name.localeCompare(item2.rows[0].name));

Upvotes: 1

Related Questions