gkrizek
gkrizek

Reputation: 1086

Sort by date field in object of array with Meteor

I have added an array of objects to my user collection in my Meteor app, called contacts. It now looks like this:

 {
    "_id" : "p6c4cSTb3cHWaJqpG",
    "createdAt" : ISODate("2016-05-11T11:30:11.820Z"),
    "services" : {
            .....
      },
  "username" : "admin",
  "emails" : [ 
    {
        "address" : "[email protected]",
        "verified" : true
    }
   ],
   "points" : 28,
   "contacts" : [ 
       {
        "when" : ISODate("2016-06-02T12:22:53.747Z"),
        "who" : "4YBufbE9PByJBkasy"
       }, 
       {
        "when" : ISODate("2016-06-02T12:00:41.833Z"),
        "who" : "EvF7DbFazmiuG86mD"
       }, 
       {
        "when" : ISODate("2016-06-02T12:21:41.415Z"),
        "who" : "MNFTSzjjzmYWgDvey"
       }
   ]
 }

I can display the contacts on my page just fine, but they are in the order that they appear in the collection. I would like to sort them by the date in the when field. Is this possible?

My helper method:

 Template.contacts.helpers({
  'cont': function(){
     var user = Meteor.user();
     return user;
   }
 });

and my Template:

 <template name="contacts">
    {{#each cont.contacts}}
        <h1><a href="/message/{{who}}">{{who}}</a></h1>
    {{/each}}
 </template>

Upvotes: 1

Views: 511

Answers (2)

gkrizek
gkrizek

Reputation: 1086

Akram Saouri was on the right track, I just needed to dig a little deeper. So I'll post the 100% working solution I came up with off that. The docs are your friend

Client.js:

 Template.contacts.helpers({
    'cont': function(){
        var contacts = Meteor.user().contacts;
        var result = contacts.sort(function (a,b) {
           if (a.when > b.when){
                return -1;
           }
           if (a.when < b.when){
                return 1;
           }
            return 0;
           });
       return result;
      }
    });

Blaze Template:

 <template name="contacts">
        {{#each cont}}
             <h1><a href="/message/{{who}}">{{who}}</a></h1>
        {{/each}}
 </template>

Upvotes: 1

Akram Saouri
Akram Saouri

Reputation: 1169

You can send the contacts array directly from the helpers and pre-sorted it like this :

 Template.contacts.helpers({
  'cont': function(){
     var user = Meteor.user();
     var contacts = user.contacts.sort({'when':'-1'})
     return contacts;
   }
 });

In this way, you blaze 'll look much simpler :

 <template name="contacts">
    {{#each contacts}}
        <h1><a href="/message/{{who}}">{{who}}</a></h1>
    {{/each}}
 </template>

Upvotes: 0

Related Questions