MeteorJS and UnderscoreJS: grouping results to plo

2019-09-03 09:14发布

问题:

I am working on a small MeteorJS app that plots points on a map based on popular areas for work.

I have this:

Template.list.jobs = function() {
  if(Session.get('currentIndustryOnet')) {
    jobs = Jobs.find({onet: Session.get('currentIndustryOnet')}).fetch();
    // Session.set('jobCount', jobs.count());

    var cnt = _.groupBy(jobs, 'address');
    console.log(cnt);

    return Pagination.collection(jobs);
  } else {
    jobs = Jobs.find()
    Session.set('jobCount', jobs.count());
    return Pagination.collection(jobs.fetch());
  }
}

The cnt variable returns a properly grouped array (the key of the array is an address like Allentown, PA). I have a collection of Cities which have ever city in the USA along with their LAT/LONGs to plot on a Google Map. So I will take the top 100 from the grouped array, find the lat/long in the Cities collection and plot those points on a map.

I am not familiar with working with a groupedBy method to sort the list based on the length and then pull out the key to use as my search.

回答1:

I'm not 100% certain about the data structure... but assuming jobs have an address field, and you want them sorted by frequency of occurrence and capped, you could do something like this:

var addresses = _.chain(jobs)
  .countBy('address')
  .pairs()
  .sortBy(function(j) {return -j[1];})
  .map(function(j) {return j[0];})
  .first(100)
  .value();

Note there may be a more clever way to use underscore to arrive at this result. Once you have the capped, sorted list of addresses, you can probably get the lat/long values via a find like:

Cities.find({address: {$in: addresses}}).fetch();