1

I have some json data which looks something like this:

const data = {
  "stores": [
    {
      "name": "s1",
      "id": "6fbyYnnqUwAEqMmci0cowU",
      "customers": [
        {
          "id": "4IhkvkCG9WWOykOG0SESWy",
          "name": "customer2",
        },
        {
          "id": "4IhkfikCG9WWOykOG0SESWy",
          "name": "customer1",
        },
        {
          "id": "9IfkvkCG9WWOykOG0SESWy",
          "name": "customer100",
        },
      ]
    },
    {
      "name": "s2",
      "id": "2D1fTgjAJ20ImiAqsWAEEI",
      "customers": [
        {
          "id": "3dfkvkCG9WWOykOG0SESWy",
          "name": "customer9",
        },
      ]
    },
    {
      "name": "s3",
      "id": "6rxmPFzIHKQ0EOAGGkAwKg",
      "customers": [
        {
          "id": "7IfkvkCG9WWOykOG0SESWy",
          "name": "customer7",
        },
      ]
    }
  ]
}

I need to sort the data as per the customers name. What I have done so far:

const sortedData = data.stores.sort(function(c1, c2) {
   return c1.customers[0].name < c1.customers[0].name;
}).map(storeInfo => (
  // Need to do something else with sorted data
)

My approach does not seem to work because I think it does not go to into nested level. Any help is appreciated.

Expected Outcome: Sort customers list(alphabetically) within each store first and then among the stores.

Hassan Abbas
  • 1,166
  • 20
  • 47

1 Answers1

1

i tried to fix that in two stages. I'm not sure about it is best but it can help to you.

const sortedData = [];

// Sort the customers for each store
for (var i = 0, len = data.stores.length; i < len; i++) {
    sortedData[i] = data.stores[i];
    sortedData[i]['customers'] = data.stores[i].customers.sort(function(c1, c2) {
        return c1.name > c2.name;
    });
}

// Sort the stores by first customer name
sortedData.sort(function(c1, c2) {
    return c1.customers[0].name > c2.customers[0].name;
});

console.log(sortedData);
akcoban
  • 953
  • 7
  • 14