Organize dates with AngularJS in ng-repeat based on the date key

Utilizing LoDash to generate statistics from records stored in an IndexedDB.

$scope.refreshStats = function() {

    var dataByMonth = _.groupBy($scope.stats, function(record) { 
        return moment(record.date).format('MMMM YYYY'); 
    });

    dataByMonth = _.mapValues(dataByMonth, function(month) {
        var obj = {};
        obj.Cars = _.groupBy(month, 'car');
        obj.Drivers = _.groupBy(month, 'driver');

        _.each(obj, function(groupsValue, groupKey) {
            obj[groupKey] = _.mapValues(groupsValue, function(groupValue) {
                return _.reduce(groupValue, function(sum, trip) {
                    sum['trips']++;
                    sum['duration']+= moment.utc(trip.duration, 'HH:mm:ss');
                    sum['total'] = moment.utc(sum.duration). format('HH:mm:ss')
                    return sum;
                }, {trips: 0, duration: 0, total:0})
            });
        })
        return obj;
    });
    $scope.statistics = dataByMonth;
    console.log($scope.statistics);
};

The output of the function consists of nested objects with keys representing a month and year combination:

Object {
    July 2016: Object, 
    August 2016: Object, 
    September 2016: Object, 
    October 2016: Object
}

An issue arises when displaying this data on the frontend as the ng-repeat directive arranges the months alphabetically (e.g., August-July-September-October) instead of chronologically. Is there a way to sort it by date?

This is how the ng-repeat loop is structured:

<div ng-repeat="(monthName, monthValue) in statistics">

    {{monthName}}

</div>

Is it possible to utilize orderBy:date when the date serves as the object key?

EDIT

My specific query pertains to identifying the Key as Date and then arranging it accordingly. Existing suggestions have not resolved this particular challenge.

Answer №1

In JavaScript, the order of keys in an object cannot be guaranteed. To ensure proper sorting, it is recommended to convert your data into {date: , value: } format and then sort it accordingly.

Here is a step-by-step guide:

var step1 = _.map(_.pairs(dataByMonth), _.partial(_.zipObject, ['date', 'value'] ));

Next, you will need to sort the data:

var step2 = _.sortBy(step1, function(value){
  return new Date(value.date);
});

The sorted values are now stored in step2 variable.

$scope.statistics = step2;

You can utilize this sorted data in your ng-repeat loop:

<div ng-repeat="montStats in statistics">

    {{monthStats.date}}

</div>

To optimize your code further:

It is advisable to keep the date as a real date to avoid parsing during each sorting iteration.

You can chain the operations like this:

_(dataByMonth).pairs().map(
  _.partial(_.zipObject, ['date', 'value'])).sortBy(function(value){
    return new Date(value);
  }).value();

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

JavaScript code must be implemented to manage unsuccessful basic authentication requests without prompting a pop-up in the browser to enter credentials

Can anyone provide me with a code snippet that effectively handles an ajax fetch error while using basic authentication, without triggering the browser's authentication pop-up? I encountered this issue while trying to retrieve a bearer token from the ...

Alignment of tooltips in Javascript map visualizations

After a developer backed out of my project near the 95% completion mark, I have been working tirelessly to finish it on my own. My current focus is on adjusting the tooltip placement for the map featured on this page: Visit here for context You can view ...

Dealing with the problem of multiple fields with unknown names can be solved efficiently by leveraging the capabilities of yup and react

How can I validate an array field with an unknown name using Yup when the field names are retrieved from a database and they all have the same validation requirements? const schema=yup.object().schema({ nameField1:yup.required('required') ...

Ways to implement a worldwide change in a subordinate entity

I am facing a challenge where I need to apply a global position, obtained from a WebVR controller, to a child object that is nested within multiple parent objects with transformations. The child object I want to update does not have any transformations app ...

Unable to interact with Angular component using selenium in Python

My goal is to be able to interact with specific buttons, spans, or inputs within an Angular application using Selenium in Python. In this case, I need to activate the search feature by clicking on a span element that contains the text test search.... Once ...

Is it possible for me to create a nested component without having to make a new file

What I desire: Home.vue <template> <div> <p>{{message}}</p> <ChildComponent/> </div> </template> <script setup> import { ref, defineComponent } from 'vue'; let message = r ...

Local client side include is failing to display the external HTML file

I'm facing a problem with my index.html file while trying to incorporate a client-side include for my footer using JavaScript. Even though I've included the "footer.htm" file, it's not displaying properly on the page. I suspect there might b ...

Utilizing a functional component to incorporate a "load more" button in ReactJS

Hey everyone, I've come across this ReactJS code that I need some help with: function DisplaySolutions({solutions}) { const topSolutions = solutions.slice(0, 4); const remainingSolutions = solutions.slice(4); const [isD ...

monitoring checkbox status in vue?

When using Vue, I have created dynamic checkboxes that display as shown below: <li v-for="element in checklist" :key="element.id" class="block w-full p-1"> <div v-if="element.taskId == task" clas ...

How to set a default option in a dropdown menu using Angular 4

Many questions have been raised about this particular issue, with varying answers that do not fully address the question at hand. So here we go again: In my case, setting the default value of a dropdown select by its value is not working. Why is that so? ...

Transforming an array into key-value pairs where the keys are odd elements and the values are even elements

Is there a straightforward way to transform this initial array: [ "Bargain", "deal", "Consistent", "Steady; regular", "Accurately", "a thing bought or offered for sale much more cheaply than is usual or expected.", "Charge", "demand (an am ...

Tips for utilizing smooth scroll through jQuery by implementing a specific class

After spending a considerable amount of time on this task, I find myself at a crossroads. In the second part of my code (as indicated), there is an anchor tag (< a >) with a class name. My goal is to implement a smooth scroll to an element based on t ...

Retrieving the IPv4 Address from an Express.js Request

I am currently working on setting up a whitelist for IP addresses in my API. However, when I use request.socket.remoteAddress in Express.js, I receive an IPv6 address (I believe) that looks like this: ::ffff:127.0.0.1. My main concern is how can I extract ...

Troubleshooting: Style not applying in AngularJS hello world application

I am relatively new to working with AngularJS and am attempting to showcase a basic "hello world". However, instead of displaying the expected output, it shows: {{"hello" + " world"}}. app.js: var app = angular.module('store', []); defaultLayo ...

Optimize Material-UI input fields to occupy the entire toolbar

I'm having trouble getting the material-ui app bar example to work as I want. I've created a CodeSandbox example based on the Material-UI website. My Goal: My goal is to make the search field expand fully to the right side of the app bar, regar ...

Increment and decrement the like count on fa-heart multiple times

Is there a way to increment the count of a fa-heart value on click and decrement it on the second click? The issue I'm facing is that I have multiple fa-heart elements on the same page, making it challenging to increment or decrement the clicked fa-h ...

You cannot use objects as a React child. The object contains the keys {seconds, nanoseconds}

Currently, I am developing a React Calendar App that utilizes Firebase. I am encountering issues when trying to display the Date for each scheduled event. Below is my App code: import React, { useState, useEffect } from 'react' import firebase f ...

Chrome Back button problem arises following interaction with Iframe in Angular

I am currently working on an Angular application that involves a specific process: Users follow a flow and end up on one of the partial pages. From this partial page, I trigger a button to fetch an ID from a cross domain using a service call (no CORS ...

The Node.js http-proxy fails to handle incoming websocket requests

After tirelessly working on this for over a week without success, I am reaching out to see if anyone can help me crack this puzzle. This question may not be straightforward to answer, unless I'm overlooking something obvious. The setup involves using ...

Using jquery.ajax to post to a single page without passing any variables

In order to capture the onclick event for a specific #id, I am retrieving form data and checking if $_POST['submit'] is set. If it is, I proceed to send an email. Although there are no errors, it appears that no data is being sent via post. < ...