MeteorJS and UnderscoreJS: grouping results to plo

2019-09-03 08:52发布

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条回答
神经病院院长
2楼-- · 2019-09-03 09:21

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();
查看更多
登录 后发表回答