Find the total duration of all items within an array by utilizing the Moment.js library

Within an array of objects, each object contains a field named "duration" that represents a string. Here is an example of one such object:

  {
    id: 14070
    project: {id: 87, name: "Test project for time tracking"}
    issue: {id: 10940}
    user: {id: 107, name: "Alexander Kirillov"}
    activity: {id: 9, name: "Development"}
    hours: 0.01
    comments: "RARA"
    spent_on: "2020-03-23"
    created_on: "2020-03-23T14:58:18Z"
    updated_on: "2020-03-23T14:58:26Z"
    custom_fields: (2) [{…}, {…}]
    start: "Mon, 23rd Mar"
    duration: "00:01" // HH:mm
    __proto__: Object
    }

The array containing these objects is named timeEntries = [{},{},...]; I am looking to calculate the total sum of all durations within the timeEntries objects using moment js. Any guidance would be greatly appreciated! Thank you in advance.

Answer №1

If you want to accomplish this task, here's how you can do it:

const timeEntries = [{
    duration: "00:01"
  },
  {
    duration: "01:00"
  },
  {
    duration: "12:30"
  }
];

const totalDurations = timeEntries.slice(1)
  .reduce((prev, cur) => {
      return prev.add(cur.duration);
    },
    moment.duration(timeEntries[0].duration));

console.log(`Total duration is: ${moment.utc(totalDurations.asMilliseconds()).format("HH:mm")}`);
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>

Answer №2

After much searching, I have discovered the resolution:

let sumOfDurations = durations.split(1).reduce(
  (previous, current) => moment.duration(current).add(previous),
  moment.duration(durations[0])
).format("HH:mm");

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

Attempting to display an HTML image utilizing data storage

I'm currently working on building a database for animals at an animal shelter. I have created tables containing species information and when a user selects a specific species, all available animals are displayed. Now, I want users to be able to click ...

Supply type Parameters<T> to a function with a variable number of arguments

I am interested in utilizing the following function: declare function foo(...args: any): Promise<string>; The function foo is a pre-defined javascript 3rd party API call that can accept a wide range of parameters. The objective is to present a coll ...

Unleashing the Power of Typescript and SolidJS: Expanding the Properties of JSX Elements

Is there a way to enhance the props of an existing JSX element in SolidJS and craft a custom interface similar to the ButtonProps interface shown in this React example below? import Solid from 'solid-js'; interface ButtonProps extends Solid.Butt ...

Implement the AngularJS orderby filter based on a checkbox selection

Is it possible to use the angularJS orderby filter with a checkbox for ordering columns? I currently have this working as expected: <tr ng-repeat="player in players | orderBy:'id':true | rangeFilter:min:max"> <td>{{player.id}}</ ...

How to return the same value as the input value in Vue before the action is completed

When creating a component and module for functionality X while using Vuex for state management, the code initially works fine. However, after the first insertion, the Getter function consistently returns the previous input value before the action is commit ...

Modifying the HTML <select> element with JavaScript

[resolved] I'm encountering an issue with the code below that is supposed to dynamically change the options in a second drop-down menu based on the selection made in the first menu. I've tried to troubleshoot the problem but haven't been suc ...

Creating an HTML table from JSON data using JavaScript

I recently wrote some code that reads the contents of an XML file and converts it into JSON. The JSON data is then displayed in an HTML table. Everything seems to be working fine, but there's one issue - the first row of the table always shows as "und ...

Utilizing various filters and sorting options on API response within Angular 8

Upon receiving the following API response: [ { "imgPaths":[ "gallery/products/55ccb60cddb4d9bded02accb26827ce4" ], "_id":"5f3e961d65c6d591ba04f3d3", "productName":" ...

"Error encountered when attempting to call the requestFocus() method on a Java applet from JavaScript

I'm encountering an issue with calling the requestFocus() method in JavaScript. Uncaught TypeError: Object #<HTMLAppletElement> has no method 'requestFocus' Below is my JavaScript code within the <head> tags: function onLoad() ...

How can JavaScript determine if this is a legitimate JS class?

I'm currently in the process of converting a React.js project to a next.js project. In my project, there's a file named udf-compatible-datafeed.js. import * as tslib_1 from "tslib"; import { UDFCompatibleDatafeedBase } from "./udf-compatibl ...

Finding a way to reference multiple components within a mapping function

In order to set a ref to each project within the map function, I am trying to pass forwardRef from child to parent. At the moment, I am only able to get a single Project. However, I need to set refs to an array list so I can work with it. Below is what I h ...

What is the best way to save an image in Node.js?

While I am extracting data from a website, I encountered the need to solve a captcha in order to access further data. I thought of presenting the captcha to the user, but the site is built using PHP and PHP-GD, complicating the process. The URL provided in ...

Is React failing to identify parameters?

working on my react project, I have an App component which is responsible for rendering multiple child components. Here's how it looks: App render() { return ( //JSX inside <BrowserRouter> <div> <Heade ...

How to easily deactivate an input field within a MatFormField in Angular

I've come across similar questions on this topic, but none of the solutions seem to work for me as they rely on either AngularJS or JQuery. Within Angular 5, my goal is to disable the <input> within a <mat-form-field>: test.component.h ...

What is the best way to utilize a component function within Vue to delete an item from an array stored in the parent's data?

It might be more helpful for you to take a look at the VueJS code related to this and then I can provide some explanation: new Vue({ el: '#app', data: { history: [ {name: 'red', value: '#f00'}, ...

A widget for Windows 7 that can handle both HTTP GET and POST requests

I'm currently working on a small gadget for our intranet and have set up a PHP file on our server for initial testing purposes. Everything seems to be functioning properly when I use the GET request method, but I would prefer to utilize POST in order ...

Obtain the name of a node using its identification number in D3JS

I am currently working on implementing a generalized tooltip feature. This tooltip will display the name and other relevant data of the active node. For example, if node 3 is currently active, the tooltip will show the name and distance (not link distance) ...

Tips for importing a library in a TypeScript file that expands a JavaScript prototype

After following the instructions provided in this question, I am experimenting with integrating Moment.js to enhance the capabilities of the Date prototype within a TypeScript project. The process of extending the Date prototype appears successful, as out ...

Sending a $.ajax post request transforming into a get

Struggling to understand the behavior of my jquery ajax request, I've hit a roadblock. function newContact() { $.ajax({ type: 'POST', contentType: 'application/json', // url: ...

Is it possible to manipulate elements within an overflow container using JavaScript/jQuery when using the HTML style "overflow:hidden"?

My <div> has a styling of style="overflow:hidden" and the size of the <body> is fixed, intended as a multi-screen display without a user interface. Is there a method to access these "invisible" elements to identify the first one that exceeds t ...