Finding distinct outcomes from an already screened roster using AngularJS

I have an array containing objects structured like this:

{
"date":"11/11/2014",
"time":"17.20.37",
"car":"396",
"driver":"Jenny",
"from":"Old Office",
"destination":"Log WH",
"pax":"3","comment":"",
"commenttime":"",
"arrival":"17.20.48",
"inserted":true,
"cancelled":"",
"duration":"00:00:11"
}

As I accumulate more data, my goal is to display statistics based on this information. For example:

November 2014 Car: 1, Number of trips: X, Time spent on the road: Y Car: 2, Number of trips: X, Time spent on the road: Y ...

October 2014 Car: 4, Number of trips: X, Time spent on the road: Y Car: 2, Number of trips: X, Time spent on the road: Y ...

I've managed to list unique month/year combinations in this way:

angular.forEach($scope.recordlist, function(record) {
  var month = moment(record.date, 'DD-MM-YYYY').format('MMMM YYYY');
  monthDict[month] = monthDict[month] || [];
  monthDict[month].push(record);
});

for (record in monthDict) {     

    for (item in monthDict[record]) {
        monthDict[record][item]['month'] = moment(record.date).format('MMMM YYYY');        
    }

};

$scope.monthlist = monthDict;
console.log($scope.monthlist);

This results in the following object structure:

Object
  November 2014: Array[5]
    0: Object
      arrival: "17.21.27"
      cancelled: ""
      car: "396"
      comment: ""
      commenttime: ""
      date: "11/11/2014"
      destination: "Gumbo Market"
      driver: "Erik"
      duration: "00:00:17"
      from: "Luna House"
      inserted: true
      month: "November 2014"
      pax: "3"
      time: "17.21.10"
      totalduration: "00:00:38"
      totaldurationdriver: "00:00:17"
    Object1: 
    Object2: 
    Object3: 
    Object4: 
  October 2014: Array[1]
    0: Object
      ...

In the view, I present it as follows:

    <div ng-repeat="(key,val) in monthlist">
      <div class="row msf-top-row">
        <div class="col-md-12">
          {{key}}
        </div>
      </div>
    </div>

This already generates a list of unique months derived from the original object list.

Now, since each array in monthlist represents a trip, I want to apply a similar filtering process to extract unique properties within each month/year object. This will allow me to list the cars that were driven in each month, the number of trips taken by each car, and the total time spent on the road for each car (totalduration = "HH.mm.ss").

In essence, I aim to filter unique elements from a previously filtered list of unique elements.

Any guidance on how to approach this? My mind is racing just thinking about it..

Answer №1

If I were to approach this, I might create something like the following:

$scope.uniqueMonths = [];

angular.forEach($scope.recordlist, function(record) {
    var month = moment(record.date, 'DD-MM-YYYY').format('MMMM YYYY');

    if( typeof $scope.uniqueMonths[month] == 'undefined'){
         $scope.uniqueMonths[month] = {
                numberOfCars : 0,
                numberOfTrips : 0,
                timeOnTheRoad: 0,
                cars : {}
        };
    }

/**
* Check and add car type for the month if it does not exist
**/
if(typeof $scope.uniqueMonths[month].cars[record.car] == 'undefined'){
    $scope.uniqueMonths[month].cars = {record.car : 1};
    $scope.uniqueMonths[month].numberOfCars++;
}

/**
* Increase number of trips as each object represents a 'trip'
**/
    $scope.uniqueMonths[month].numberOfTrips++;

/**
* Update the total seconds spent on the road. 
* Conversion to integer is necessary.
**/

    $scope.uniqueMonths[month].timeOnTheRoad = $filter('secondsFmt')(record.duration);

});

For the filter.js file:

angular.module('myapp', []).filter('secondsFmt', function(){
    return function(time) {
        var totalSeconds = 0;
        var times = time.split(':');
        totalSeconds += parseInt(times[0]) * 3600;
        totalSeconds += parseInt(times[1]) * 60;
        totalSeconds += parseInt(times[2]);
    return totalSeconds;
    };
});

This is my suggestion. Feel free to reach out if you have any inquiries.

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

Refresh a div using jQuery and include PHP files for dynamic content updating

This is the code I am using to dynamically update divs containing PHP files: $(document).ready(function() { setInterval(function() { $('#ContentLeft').load('live_stats1.php').fadeIn("slow"); $('#ContentRight').load( ...

Accessing a Variable in one JavaScript File from Another JavaScript File

In the process of creating a basic game using only JavaScript and jQuery, I have split it into two separate pages. The first page contains all the rules and necessary information, while the second page is where the actual game takes place. My goal is to in ...

Alternative method to jQuery's "find" selector

$('.wrapper a').filter('a'); //returns all anchors I am trying to find a way to select all anchor elements using a specific selector. The issue is that the find method only looks at descendants, so I need an alternative solution. Any s ...

Encountering a problem with the JavaScript promise syntax

Using pdfjs to extract pages as images from a PDF file and then making an AJAX call to send and receive data from the server is proving to be challenging. The implementation for iterating through the pages in the PDF was sourced from: The issue lies in pr ...

typescript mock extending interface

I'm currently working with a typescript interface called cRequest, which is being used as a type in a class method. This interface extends the express Request type. I need to figure out how to properly mock this for testing in either jest or typemoq. ...

Steps to Change the Background Color to White in a Dropdown menu

Hello everyone! I'm currently using this codepen example on my website. My query is regarding the fifth panel - is it possible to change the color of the drop-down box when clicking on it? Here's a snippet of the HTML: <link href='https: ...

What is the reason behind this code's ability to detect vowels as well as other

I'm currently working on debugging a specific portion of code for my class. I'm having trouble understanding why this JavaScript code is counting all letters instead of just vowels. var text, i, sLength, myChar; var count; var text = prompt("Ple ...

How to Animate the Deletion of an Angular Component in Motion?

This stackblitz demonstration showcases an animation where clicking on Create success causes the components view to smoothly transition from opacity 0 to opacity 1 over a duration of 5 seconds. If we clear the container using this.container.clear(), the r ...

Problem with Ionic App crashing

Currently, I am developing an Ionic app that relies on local storage for offline data storage. The app consists of approximately 30 different templates and can accommodate any number of users. Local storage is primarily used to store three key pieces of i ...

Click the button on your mobile device to open the already installed Android app

After creating a small Android app using jQuery Mobile, I incorporated a button to open another native Android app. Is it feasible for the jQuery Mobile app button to load/open an already installed and functioning native Android app upon click? I would gr ...

Using a Hook inside a React function is not possible

I encountered an error message known as the "invalid hook call error" while using the useEffect hook in my code. According to the documentation, this issue usually arises due to either a version mismatch or incorrect function calls. Could someone kindly r ...

Guide on how to retrieve the parent element's number when dragging starts

Within my div-containers, I have a collection of div-elements. I am looking to identify the parent number of the div-element that is currently being dragged For example, if Skyler White is being dragged, the expected output should be "0" as it is from the ...

Can you explain the functionality of `module.exports = mongoose model` in a NodeJs environment

Coming from a front-end React background, I am familiar with statements like import and exports. However, as I delve into learning Backend (NodeJs) with mongoDB, I find myself curious about the mechanics of import and export in this new environment. I hav ...

What is the best approach to integrating AJAX calls with promises in the Angular framework?

I'm facing an issue while using Angular promises with the $q service in my controller. Here's the code snippet: var myController = function ($scope, myService) { $scope.doSomething = function (c, $event) { $event.preventDefault(); ...

Invoke a jQuery method in a dynamic manner

Is it possible to achieve the following? var todo = "text"; $this.eval(todo).split(/\b[\s,\.-:;]*/).length; The desired function is: $this.text().split(/\b[\s,\.-:;]*/).length; I'm struggling to find a solution... Ca ...

Developing a unique data type in Umbraco version 7.3 without relying on AngularJS

I am interested in developing a custom data type in Umbraco 7.3 without relying on AngularJS, however, my lack of knowledge about AngularJS is holding me back. After conducting some research online, I discovered that all the available examples are based o ...

Angular 2: How to Round Numbers for Percentage Calculations

What is the formula to convert a decimal number into a percentage? For example, if the number is 0.050, how can I display it as 5.0? The number is retrieved from a database in decimal form but needs to be shown as a percentage. Current code snippet: ...

JQuery integration resulting in disappearance of Input-group-btn element

Allow me to explain my current project. I am in the process of developing a Modal that enables users to input a password There will be an option to toggle between showing or hiding the text in the password field using a button positioned on the right sid ...

AngularJS Unleashed: The Art of Displaying Dynamic AJAX

Hey there, I have a concern about the best practice to show or hide an ajax loading animation while input/output operations are being performed. At present, I am managing the animation using this code: Javascript app.controller('MyController', ...

Getting row data from ag-grid using the angular material menu is a straightforward process

I have a specific requirement in ag-grid where I need to implement a menu to add/edit/delete row data. Currently, I am using the angular material menu component as the cell template URL. However, I am facing an issue where when I click on the menu item, it ...