Displaying the combined total for each date

My goal is to calculate the total for each department without duplicates ( which is currently working ) and display all results based on the selected date.

I intend to select a date using md-datepicker and then only display the total task time where the date matches the selected date.

This is the HTML section:

<body ng-app="ngrepeatSelect">
    <div ng-controller="ExampleController">
        <form name="myForm">
            <md-datepicker ng-model="myDate" md-placeholder="Enter date" ng-change="sum(myDate)"></md-datepicker>
            {{myDate}}
            <tt>model = {{data.model}}</tt>
            <br/>
            <hr/>
        </form>
        <md-table-container>
            <table md-table>
                <thead md-head>
                    <tr md-row>
                        <th md-column>Dept</th>
                        <th md-column>Total time</th>
                        <th md-column></th>
                    </tr>
                </thead>
                <tbody md-body>
                    <tr ng-if="!data.model" md-row md-select="test" md-on-select="" md-auto-select ng-repeat="test in tests">
                        <td md-cell>{{ test.dept }}</td>
                        <td md-cell>{{ test.total }}</td>
                        <td md-cell></td>
                    </tr>

                    <tr ng-if="data.model" md-row md-select="test" md-on-select="" md-auto-select ng-repeat="(key,val) in data.model">
                        <td md-cell>{{ key }}</td>
                        <td md-cell>{{ val }}</td>
                        <td md-cell></td>
                    </tr>
                </tbody>
            </table>
        </md-table-container>
    </div>
</body>

and JavaScript

angular.module('ngrepeatSelect', ['ngMaterial'])
    .controller('ExampleController', function($scope, $filter) {
        $scope.myDate = '';

        $scope.$watch('myDate', function(newVal, oldVal) {
            if (!newVal) {
                return false;
            }
            var date = $filter('date')(new Date(newVal), "yyyy-MM-dd");
        });

        var data = [{
            id: "1",
            user: "John Doe",
            dept: "test",
            date: "2017-03-02",
            task_time: "83"
        }, {
            id: "2",
            user: "Mark Doe",
            dept: "test",
            date: "2017-02-02",
            task_time: "41"
        }, {
            id: "3",
            user: "Zac Doe",
            dept: "other",
            date: "2017-02-04",
            task_time: "12"
        }, {
            id: "4",
            user: "Zac Doe",
            dept: "test",
            date: "2017-03-02",
            task_time: "41"
        }, {
            id: "5",
            user: "Zac Doe",
            dept: "test",
            date: "2017-03-02",
            task_time: "41"
        },{
            id: "6",
            user: "Zac Doe",
            dept: "test2",
            date: "2017-03-02",
            task_time: "41"
        },{
            id: "7",
            user: "John Doe",
            dept: "test",
            date: "2017-01-02",
            task_time: "41"
        },{
            id: "8",
            user: "Zac Doe",
            dept: "test",
            date: "2017-01-01",
            task_time: "41"
        },{
            id: "9",
            user: "John Doe",
            dept: "tests",
            date: "2017-02-12",
            task_time: "41"
        }, {
            id: "10",
            user: "Zac Doe",
            dept: "test2",
            date: "2017-02-13",
            task_time: "53"
        }];

        var totalPerDept = [];

        angular.forEach(data, function(item) {
            var index = findWithAttr(totalPerDept, 'dept', item.dept);

            if (index < 0) {
                totalPerDept.push({
                    dept: item.dept,
                    total: parseFloat(item.task_time)
                });
            } else {
                totalPerDept[index].total += parseFloat(item.task_time);
            }
        });
        $scope.tests = totalPerDept;

        function findWithAttr(array, attr, value) {
            for (var i = 0; i < array.length; i += 1) {
                if (array[i][attr] === value) {
                    return i;
                }
            }
            return -1;
        }


        $scope.sum = function(date) {
            let model = data.filter(function(item) {
                return (item.date == TheSameDate(item))
            });

            let tests = {};
            model.forEach(function(item) {
                if (!tests.hasOwnProperty(item.dept)) {
                    tests[item.dept] = 0;
                }

                tests[item.dept] += parseFloat(item.task_time);

            });

            $scope.data.model = tests;
        }

        function TheSameDate(item){
            if($scope.myDate){
            let myDate = new Date($scope.myDate);
            let itemDate = new Date(item.date);

            if(myDate.getFullYear() != itemDate.getFullYear() || myDate.getMonth() != itemDate.getMonth()){
                return false;
            }
          }

          return true
        }


        $scope.data = {
                current: null,
            model: null,
            availableOptions: [{
                    id: '1',
                    name: 'John Doe'
                },
                {
                    id: '2',
                    name: 'Mark Doe'
                },
                {
                    id: '3',
                    name: 'Zac Doe'
                }
            ]
        };


    });

I have set up a JSFiddle showcasing the functionality I am aiming to achieve.

Answer №1

I have optimized your code by revising the date comparison logic.

Instead of separate conditions, I have integrated the date equality check within the filter function as shown below:

let filteredData = data.filter(function(item) {
    let itemDate = new Date(item.date);
    return (
        itemDate.getFullYear() === selectedDate.getFullYear() &&
        itemDate.getMonth() === selectedDate.getMonth() &&
        itemDate.getDate() === selectedDate.getDate()
    );
});

Live Demo

Click here for a live demonstration

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

There was an issue with the Discord.js (v12) Giveaway Command that resulted in an error stating "Error: Cannot read property 'hasPermission' of undefined"

Hey everyone, I'm trying to develop my own Discord bot and I want to add a giveaway command to it. I found an example code online that I tried to implement, but unfortunately, it's not working as expected... const ms = require('ms'); c ...

Transferring an IONIC project to a different computer

Let me outline the current situation I am facing - I primarily work as a firmware developer rather than a software developer. Recently, a team member who was responsible for developing the front end of an application in IONIC has left the company, leaving ...

Ways to specify the styles for tr, td, and label elements within a material table

Hey there! Currently, I'm working with material table in react. I came across this page: https://material-table.com/#/docs/features/styling, where it mentions that we can use cellStyle, headerStyle. But what if I want to add more detailed styles to e ...

Angular.js: Utilizing ng-model for checkboxes

Here's the code for my project: <input type="checkbox" ng-model="variable"> In this scenario, the variable will hold either true or false based on the checkbox status. However, I want it to store "+" instead of true and "-" instead of false. W ...

What specific data am I sending from my ajax request to the MVC controller?

How can I determine the appropriate parameter to use when passing a JavaScript object? Please see below: var all = []; //iterate through each instrument for (var i = 0; i < 3; i++) { var txt = getThis(i);//int var detail =getThat(i);//string ...

Erase a set of characters with the press of the backspace key (JavaScript)

Within my textarea, I have lines that start with a number and a period: <textarea autoFocus id="text-area"wrap="hard" defaultValue ={this.state.textAreaVal} onKeyUp={this._editTextArea}/> For example: Line 1 Line 2 Line 3 I've created a ...

Illuminate objects using three.js

My expertise in shaders and three.js is limited, however I am currently experimenting with creating a dynamic glowing effect similar to lights being flicked on and off. Currently, I am adjusting the color saturation and lightness which somewhat achieves ...

Each container has its own div counter

Help needed to complete this code. The task is to count the number of .resp-containers in each container separately. Then, based on that count, assign a corresponding class to each element within the containers. Check out the code here $(document).ready(f ...

Finding the Client's Private IP Address in React or Node.js: A Comprehensive Guide

Issue I am currently facing the challenge of comparing the user's private IP with the certificate's IP. Is there a method available to retrieve the user's private IP in react or node? Attempted Solution After attempting to find the user&a ...

What sets apart "import { pick } from 'lodash';" from "import pick from 'lodash/pick';"?

Can you explain the difference between import { pick } from 'lodash'; and import pick from 'lodash/pick'; (Keep in mind that it's 'lodash/pick' in the second one, not just 'lodash'.) How do they each impact ...

Avoiding double entries in the shopping list using DOM selectors in JavaScript

I have been struggling with preventing duplicate items from being added to a shopping list that I created. Even though I thought the code below would solve the issue, it hasn't been effective so far. My expectation was for the JavaScript code to acces ...

Combining two arrays with varying lengths based on their values

Seeking assistance with a programming task that is straightforward yet challenging for me. There are two arrays: one long and one short. var arrayShort = [ { id: 'A', name: 'first' },{ id: 'B', name: &ap ...

Issue regarding angularjs type definitions

I am facing an issue with installing typings for Angular and I need some guidance on how to resolve the error. Any suggestions or assistance would be greatly appreciated! Below is the error message that I encountered: ERROR in C:\Users\test&b ...

Utilizing the Masonry jQuery plugin for optimizing empty spaces

Recently, I came across the Masonry plugin and I'm considering using it in a project. One question that intrigues me is whether there is a way to detect empty spaces that occasionally show up in the layout when divs are positioned. Being able to ident ...

Differentiate the items within a list containing identical divs using JavaScript

Currently, I am expanding my knowledge in HTML, CSS, and JS by incorporating Angular and JQuery. In one of my projects, there is a div labeled "eventBoxes" where multiple divs known as "eventBox" can be added. I have created a template for the eventBox i ...

Is there a way to dynamically create a Vue component for every tier of a nested JSON object without prior knowledge of the total number of tiers available?

I am working with JSON data that includes a list of retailers, some of which have subretailers that go multiple levels deep. My goal is to use Vue to generate markup that will show the parent retailer along with any nested subretailers underneath it, simi ...

Control the scope value using an AngularJS directive

I have a model with values that I need to modify before presenting them to the user. I have checked the documentation but might be overlooking something. For example, I would like to format my variable in this way: <span decode-directive>{{variable ...

Tips on incorporating Prisma model into prisma-offset-pagination

I am currently implementing pagination using the prisma-offset-pagination package. To do this, I need to utilize Prisma Model in my code, but I'm unsure of the correct approach: Refer to line: 02 const result = prismaOffsetPagination({ model: user ...

What is the best way to ensure that a div containing lengthy text wraps to the next line as if it were only text overflow?

Is there a way to make a div or span within another div act as text, causing overflow to shift to the next line? I'm unsure of which CSS properties would achieve this effect. I've attempted using overflow-wrap: break-word; word-break: break-al ...

PHP/MySQL clarification regarding time slots

Could someone assist me with this discussion I found? Due to my low reputation, I am unable to comment for further clarification. Although I grasp the solution provided in the mentioned discussion, I am struggling to comprehend how to pass the data to my ...