Search code examples
meteormeteor-autoform

Sort array based on startDate


I'm trying to sort an array and not having much luck. If I remove the helper I print out the all the qualifications in the order they went into the database. I would like to display them chronologically based on their startDate.

Path: dbExample

"profile": {
    "CV": {
      "education": [
        {
          "qualification": "Arts Degree",
          "startDate": "2009-01-01T00:00:00.000Z",
          "endDate": "2013-12-01T00:00:00.000Z"
        },
        {
          "qualification": "Science Degree",
          "startDate": "2007-01-01T00:00:00.000Z",
          "endDate": "2008-12-01T00:00:00.000Z"
        }
      ]
    }
}

Path: education.html

<template name="education">
    {{#each educationHistory}}
    <div class="box">
        <p class="title">{{qualification}}</p>
        <p class="dates">{{startDate}} - {{endDate}}</p>                
    </div>
    {{/each}}
</template>

Path: education.js

Template.education.helpers({
    educationHistory: function () {
        return Meteor.users.find({}, {sort: {"startDate": 1}});     
    }
});

Path: Schema.js

Schema.Education = new SimpleSchema({
    qualification: {
        type: String,  
        optional: true    
    },
    startDate: {
        type: Date,  
        optional: true 
    },
    endDate: {
        type: Date,  
        optional: true  
    }
});

Schema.CV = new SimpleSchema({
    education: {
        type: [Schema.Education],
        optional: true
    }
});

Solution

  • This is a little hard to follow because I don't know the context of the template or which user's education history to use. Here are a couple of solution ideas:

    solution 1

    Template.education.helpers({
      educationHistory: function () {
        // replace Meteor.user() with Meteor.users.findOne(someId) or something
        const { education } = Meteor.user().profile.CV;
        return _.sortBy(education, e => e.startDate);
      },
    });
    

    This returns an array of education objects, sorted by startDate.

    solution 2

    If the template already has an educationHistory without the helper (based on your comments below), then you can replace the educationHistory helper with this:

    Template.education.helpers({
      sortByStartDate: function (education) {
        return _.sortBy(education, e => e.startDate);
      },
    });
    

    Then in your template:

    <template name="education">
      {{#each sortByStartDate educationHistory}}
        <div class="box">
          <p class="title">{{qualification}}</p>
          <p class="dates">{{startDate}} - {{endDate}}</p>
        </div>
      {{/each}}
    </template>