List the hours using TypeScript

My data table is displaying records including a column for hours spent and a row showing the total sum of those hours. While the hours are being added correctly, the minutes display as NaN, such as 52:Nan. Can someone assist me in resolving this issue?

component.ts

empPageChange(event) {
    let list = this.timetables.slice(event.first, event.first + event.rows);
    if (list.length > 0) {
        this.totalHoursSpent = HelperService.addTimes(list, 'HoursSpent');
    } else {
        this.totalHoursSpent = 0;
    }
}

helper.service.ts:

 static addTimes(timeMap, columnName: string) {
    let totalH = 0;
    let totalM = 0;

    // First simply adding all of it together, total hours and total minutes
    for (let x in timeMap) {
        if (x) {
            let timeArray = timeMap[x][columnName].split(':');
            let hour = timeArray[0];
            let minutes = timeArray[1];
            totalH += parseInt(hour, 10);
            totalM += parseInt(minutes, 10);
        }
    }

    // If the minutes exceed 60
    if (totalM >= 60) {
        // Divide minutes by 60 and add result to hours
        totalH += Math.floor(totalM / 60);
        // Add remainder of totalM / 60 to minutes
        totalM = totalM % 60;
    }
    return `${totalH}:${
        totalM.toString().length === 1 ? `0${totalM}` : totalM
        }`;
}

Answer №1

Given the presence of NaN, there are a few things to consider:

  • Have you verified that your timeArray consists only of numbers? You might want to use console.log(timeArray[1]) to confirm this. Also, check the value of the TotalM variable.

  • Could it be possible that your minutes are in decimal form? If so, and if your current culture uses "." as a decimal separator, this could cause the issue of NaN.

    isNaN(Number("10,5")) //true

    isNaN(Number("10.5")) //false

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

CLI package enables exporting API facilities

I have a mono repository containing a CLI package (packages/cli) and a web application (apps/web). I want to utilize the public API of the CLI within the web app. The CLI package is packaged with tsup: export default defineConfig({ clean: false, dts: ...

How do I utilize the file handler to execute the flush method within the Deno log module using Typescript?

I'm having trouble accessing the fileHandler object from my logger in order to flush the buffer to the file. This is the program I am working with: import * as log from "https://deno.land/<a href="/cdn-cgi/l/email-protection" class="__cf_emai ...

Is there a way to integrate a calendar feature within an Angular 2 application?

I am brand new to Angular 2 and have a question: I need to integrate a calendar into a page where users can add events. Something similar to the following example: I'm unsure if the angular material calendar project is designed for Angular 2 or for ...

TypeScript Implementation of ES6 Arrow Functions

Just diving into Typescript, I'm struggling to figure out the solution. I tried researching and looked into destructuring, but still unable to make it work. import React from "react"; import { StyleSheet, Text, View } from "react-native"; const st ...

Why is it necessary to define a property outside the constructor in Typescript, when in Javascript I wouldn't have to do that?

When working with Javascript, creating a class like the one below allows us to avoid declaring and initializing a property named logs outside of the constructor: class Logger { constructor() { this.logs = []; } } However, transitioning to TypeScri ...

Deleting a property once the page has finished loading

My issue is a bit tricky to describe, but essentially I have noticed a CSS attribute being added to my div tag that seems to come from a node module. The problem is, I can't seem to find where this attribute is coming from in my files. This attribute ...

Identify alterations in a variable and trigger an event

I have a button labeled 'Refresh Data' that triggers the refreshBatchData() function: refreshBatchData(){ this.homeService.refreshData().subscribe(data => { this.batchSpotData = data; }) } After receiving data in batchSpo ...

Functionality not functioning within Shadow DOM

After creating and exporting an Angular Element as a single script tag (user-poll.js), using the element on a host site is simple. Just include the following two lines: <user-poll></user-poll> <script src="path/to/user-poll.js"></sc ...

What is causing the incompatibility of these generic props?

I am encountering compatibility errors when using two React components that have props accepting a generic parameter TVariables. These props include the fields variables of type TVariables and setVariables of type (vars: TVariables) => void. Even thoug ...

The paths configuration in tsconfig.json is not functioning as anticipated

I've been encountering a module not found error while trying to work with jasmine-ts. To troubleshoot, I decided to use tsc and inspect my folder structure: \src\app\... \src\tests\... To address this issue, I created a ...

Error management and callback handling in MSAL.js for Angular 6 Single Page Applications

I am currently using msal.js in an angular 6 SPA for authentication purposes, but I have encountered a few issues: Initially, I struggled to find clear examples on how to handle errors with the library, so I pieced together information from various source ...

Angular 2 and beyond: Managing an array of objects with nested subscriptions using the forEach method

My scenario involves working with two separate Observables. The first one is used to retrieve a list of items, which comes back as an array of objects with a key called "fakturaId": getInvoiceForResidence() { return this.httpClient.get<Invoices> ...

"Zone has been successfully loaded" - incorporating angular universal ssr

I am currently working on an Angular project and I am looking to implement server-side rendering. To achieve this, I decided to use Angular Universal. The browser module of my project was successfully built, but I encountered the following issue during the ...

Display the React component following a redirect in a Next.js application that utilizes server-side rendering

Just starting out with next.js and encountering a problem that I can't seem to solve. I have some static links that are redirecting to search.tsx under the pages folder. Current behavior: When clicking on any of the links, it waits for the API respo ...

Creating a universal parent constructor that can take in an object with keys specific to each child class

I am looking to create a base class with a constructor that allows for all the keys of the child class to be passed. However, I am facing a challenge because 'this' is not available in constructors. Here is what I hope to accomplish: class BaseCl ...

Issue with Angular app using Azure AD not redirecting to specified path after successful login

My angular webapp is connected to Azure AD/Entra Id for user authentication. The redirect URI in my Azure AD app is set as "http://localhost:4200/translate". Here are my defined routes: const routes: Routes = [ { path: 'translate', path ...

Mapped Generics in Typescript allows you to manipulate and

Currently, I am attempting to utilize TypeScript generics in order to transform them into a new object structure. Essentially, my goal is to change: { key: { handler: () => string }, key2: { hander: () => number }, } to: ...

When working on styling a different Styled Component, how should one define the type of props required?

I'm currently working on a NextJS project using styled components and typescript. I have customized a div element like this: export const ClippedOverlay = styled( ( props: React.DetailedHTMLProps< React.HTMLAttributes<HTMLDivElement& ...

Angular's Enhanced Feature: Selecting Multiple Columns

Looking for an open-source Angular library that can display items in multiple columns rather than each item spanning across multiple columns. Many libraries support tabular display, but the challenge is to find one that arranges items in multiple columns. ...

I recently installed Angular version 12, but another unexpected version 13 was also installed simultaneously. I only wanted version 12, so now I need to figure out how to uninstall

C:\Users\eaind>npm install -g @angular/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="96f5faffd6a7a4b8a6b8a4">[email protected]</a> https://i.sstatic.net/LQPPT.png Upon installing version 12 in the direc ...