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.

8
  • You're not sorting customers, you are sorting the stores by their first customer's name. What do you expect as the output? Commented Sep 13, 2018 at 14:08
  • return x < y is not enough Commented Sep 13, 2018 at 14:09
  • Do you want to sort the customers array by name within each single store? Commented Sep 13, 2018 at 14:13
  • @AntonioPangallo, updated the question Commented Sep 13, 2018 at 14:21
  • You could sort it with lodash: const sortedData = _.sortBy(data.stores, o => o.customers.name); console.log(sortedData); Commented Sep 13, 2018 at 14:41

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.