Arrange objects in an array by the date field using Meteor

I have updated my user collection in my Meteor app with an array of objects named contacts. This is how it looks now:

 {
    "_id" : "p6c4cSTb3cHWaJqpG",
    "createdAt" : ISODate("2016-05-11T11:30:11.820Z"),
    "services" : {
            .....
      },
  "username" : "admin",
  "emails" : [ 
    {
        "address" : "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="43262e222a2f03262e222a2f6d202c2e">[email protected]</a>",
        "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"
       }
   ]
 }

Although I can successfully display the contacts on my page, they are currently in the same order as they are in the collection. Is it possible to arrange them based on the date in the when field?

This is my helper method:

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

And this is my Template:

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

Answer №1

Akram Saouri provided valuable guidance, leading me in the right direction to find a solution. After delving deeper into the problem, I was able to come up with a foolproof solution. Make sure to refer to official documentation for additional insights.

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>

Answer №2

If you want to streamline the process, you can directly send the contacts array from the helpers and have it pre-sorted like this:

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

By doing this, your Blaze template will appear much cleaner and simpler:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Simulate a keyboard key being pressed and held for 5 seconds upon loading the page

Is it possible to create a script that automatically triggers an event to press and hold down the Space key for 5 seconds upon page load, without any user interaction? After the 5 seconds, the key should be released. It is important to emphasize that abso ...

The functionality of Webdriver.waitUntil is not meeting the expected outcomes

I'm currently utilizing webdriverio version 4.5: ./node_modules/.bin/wdio -v v4.5.2 In my scenario, I am in need of waiting for the existence of a specific element and handling the situation if it doesn't exist. Here is an example code snippet ...

Using Django Sessions for User Authentication in React Applications

Not a coding query, but rather a general one: When using default authentication in Django (session authentication), what does the frontend (in my case it's React) require? For instance, upon logging in on the browser via the front end login button, th ...

I have a task to execute an Ajax request to retrieve and display data from my database table. My approach involves utilizing Perl CGI and attempting to invoke a Perl script using JavaScript

Encountering an issue in the web console with an error in the document.ready function showing an uncaught syntax error unidentified identifier. This CGI script contains JavaScript that calls a Perl script (TestAj.pl) which returns JSON data. I'm atte ...

Converting an unbroken series of string values into organized key-value pairs for easy reference

I assure you this is not a duplicated question. Despite my attempts with JSON.parse(), it seems to be ineffective. Here's the issue at hand: I recently received assistance from an answer that was both crucial and enlightening. However, the code prov ...

Angular error: Trying to assign a value of type ArrayBuffer to a string type

Is there a way to display a preview of a selected image before uploading it to the server? Here is an example in HTML: <div id="drop_zone" (drop)="dropHandler($event)" (dragover)="onDragover($event)"> <p>drag one or more files to ...

Exploring Mongoose Querying

Currently, I am tackling a mongoose query focusing on nested data handling. An illustration of the data: { name : 'blah', en : { state : 'published', pubDate : '2015-10-19-22T13:44:16.387Z' }, es : { ... ...

What is causing the components to not re-render after a state change in React?

I am attempting to retrieve data from the Coin Market Cap API and showcase the details in simple cards. I have experimented with various methods and included comments to document my trials. Any assistance would be greatly appreciated. This is the Parent: ...

Tips for hiding a soft keyboard with jQuery

Here is a text button: <input type="text" class="field" id="something" name="something" placeholder="text" autofocus /> I want to prevent the android soft keyboard from popping up and keep the focus on this field. I only want to do this for this ...

Encountering difficulty locating the $wpdb variable during an AJAX request

I am currently developing a PHP application for WordPress and facing a challenge in retrieving a value from a database using AJAX every 2 seconds. I have created a new function in a separate file to handle this task. <?php global $wpdb; function retrie ...

`req.user` seems to be unresolved, but it is actually defined

Currently, I am working on developing an Express.js application that utilizes Passport.js for authentication in an administration panel. The program is functioning correctly at the moment, with my app.js initializing passport and setting up sessions proper ...

How can we display or conceal text indicating the age of a patient based on the value returned from selectedPatient.age in a React application?

Hello, I am looking to dynamically display the age in years on the screen based on the value retrieved from selectedPatient.age, toggling between visible and hidden states. import React, { useContext } from 'react'; import { useHistory } from &ap ...

Dealing with errors when Ajax response is not defined

Trying to display errors when Ajax is unsuccessful, but struggling to access the specific error details. example Here is the information from the network tab playground {"message":"The given data was invalid.","errors":{"title":["The title field is requ ...

Steps for displaying a customized view within an NPM module:

Given that pushAsset prohibits loading external resources, I am interested in displaying this template/script from my NPM module: views/tag.html <script async src="https://www.googletagmanager.com/gtag/js?id={{ data.gid }}"></script> NPM mod ...

The combination of Three.js and React

Hello everyone! I am completely new to Three.js and I'm currently attempting to integrate it with React. While looking for resources, I came across this helpful medium article on the topic: Starting with React 16 and Three.js in 5 minutes My goal is ...

Experiencing difficulties with updating populated inputs that are connected to fetched data as they are not reflecting changes when modified

I am currently facing challenges with handling text fields in my web application. I need to retrieve data from the database, populate it in the appropriate fields, allow users to edit the information, and save any changes made. However, I have encountered ...

Utilizing jQuery to Trigger a Click Event on an Element Without a Class

What is the best way to ensure that the "click" event will only be triggered by an href element unless it does not have the "disablelink" class? Avoid processing the following: <a class="iconGear download disablelink" href="#">Download</a> P ...

I'm confused why this code is functioning in JSFiddle but not on my HTML webpage

For the first time, I am encountering this issue. I am currently attempting to integrate this code into my application http://jsfiddle.net/TC6Gr/119/ My attempts include: Pasting all the jsfiddle code in a new page without my code, but it doesn't w ...

Angular developers are struggling to find a suitable alternative for the deprecated "enter" function in the drag and drop CDK with versions 10 and above

By mistake, I was working on an older version of Angular in StackBlitz (a code-pane platform). I came across a function called enter on GitHub, but it didn't solve my issue. I was working on a grid-based drag and drop feature that allows dragging bet ...

Integrating Javascript and JQuery in Reactjs: A Comprehensive Guide

Currently, I am working with ReactJS and utilizing the Next.js framework. My goal is to implement the provided code snippet in index.js to display data (day, month, etc.). How should I go about achieving this? Here is the code snippet: <script> fun ...