0

Having a very large collection of objects structured like this:

[
  {
    "name": "john",
    "job": "cop",
    "city": "london"
  },
  {
    "name": "mike",
    "job": "nurse",
    "city": "las vegas"
  },
  {
    "name": "kate",
    "job": "teacher",
    "city": "london"
  }
]

I'm trying to iterate through them in order of city. Pseudo-code:

For each city
    print some extra city info
    For each person in city
        print person info
    next
    print some other extra city info
next

I know how to do this in a complicated way; is there a simple one using JQuery?

4
  • please share what ever you have tried Commented Jun 3, 2014 at 3:52
  • 1
    Could you show the actual data structures, not some generic description of them. Is the collection an array? Use sort to sort it by city, then use jQuery.each() to iterate over them. Commented Jun 3, 2014 at 3:55
  • @ArunPJohny The way I would do it would be very hacky and long, so I haven't tried it yet (also because I know it WILL work). I'm looking for the simpler/best way to do it. Commented Jun 3, 2014 at 7:48
  • @Barmar Question amended to include the actual data structure Commented Jun 3, 2014 at 7:49

1 Answer 1

1

First sort the info by city:

info.sort(function(i1, i2{
    if (i1 < i2) {
        return 1;
    } else if (i1 > i2) {
        return -1;
    } else {
        return 0;
    }
});

Then iterate over the elements, printing the city info whenever it changes.

var last_city = null;
$.each(info, function(i, el) {
    if (el.city != last_city) {
        // print extra city info
    }
    // print person info
    if (el.city != last_city) {
        // print more city info
        last_city = el.city;
    }
});
Sign up to request clarification or add additional context in comments.

1 Comment

As easy as that. Thank you!

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.