JavaScript - combining elements of an array of time

I've encountered a challenge where I need to calculate the total time duration from an array that contains time durations like

['00:30', '01:30', '03:00', '04:30']
. The code snippet I'm using for this task seems to be producing unexpected results such as 00000.5010.503040.5:0. Has anyone faced a similar issue when trying to sum up time durations before?

function calc_tot_dur() {
  var total_durs = ['00:30', '01:30', '03:00', '04:30'];
  var dim = '00:00';
  jQuery.each(total_durs, function(index, value) {
    //console.log(value);
    dim_split = dim.split(":");
    hs = dim_split[0];
    ms = dim_split[1];

    value_split = value.split(":");
    v_hs = value_split[0];
    v_ms = value_split[1];
    console.log(hs + v_hs);
    dim = (hs + v_hs) + ':' + (ms + v_ms);
    // console.log(dim);
    ms_hs = (ms + v_ms) / 60;
    if (ms_hs > 0) {
      dim = (hs + v_hs + ms_hs) + ':' + (00);
    } else {
      dim = (hs + v_hs) + ':' + (ms + v_ms);
    }
  });
  alert(dim);
}

Answer №1

Using the reduce method, here's a solution along with an adjustment for the length of the parts.

var total_durations = ['00:30', '01:30', '03:00', '04:30'],        
    final_result = function (arr) {
        var sum = arr.reduce(function (accumulator, currentValue) {
                var timeArray = currentValue.split(':').map(Number);
                return accumulator + 60 * timeArray[0] + timeArray[1];
            }, 0);

        return [Math.floor(sum / 60), sum % 60].map(function (time) {
            var stringValue = time.toString();
            return stringValue.length < 2 ? '0' + stringValue : stringValue;
        }).join(':');
    }(total_durations);

document.write('<pre>' + JSON.stringify(final_result, 0, 4) + '</pre>');

Answer №2

There are some missing parseInt calls in certain parts of the code, causing unexpected results when summing values.

"00" + "00" //concatenates strings to become 0000
parseInt("00") + parseInt("00") //sums as integers to become 0

To fix this issue:

function calculate_total_duration() {
  var total_durations = ['00:30', '01:30', '03:00', '04:30'];
  var base_time = '00:00';
  jQuery.each(total_durations, function(index, value) {      
    base_split = base_time.split(":");
    base_hours = parseInt(base_split[0]);   // parse integer here
    base_minutes = parseInt(base_split[1]); 

    value_split = value.split(":");
    value_hours = parseInt(value_split[0]);  
    value_minutes = parseInt(value_split[1]); 
    base_time = (base_hours + value_hours) + ':' + (base_minutes + value_minutes);

    minutes_to_hours = parseInt((base_minutes + value_minutes) / 60);   
    if (minutes_to_hours > 0) {
      base_time = (base_hours + value_hours + minutes_to_hours) + ':' + '00';
    } else {
      base_time = (base_hours + value_hours) + ':' + (base_minutes + value_minutes);
    }
 });
 console.log(base_time);
}

Answer №3

If you're looking to streamline your date and duration handling in JavaScript, consider giving Moment a try. This powerful library is perfect for simplifying these tasks. Take a look at this demo on JSFiddle to see it in action:

https://jsfiddle.net/25zfe4h1/

function calculateTotalDuration() {
  var totalDurations = ['00:30', '01:30', '03:00', '04:30'];
  var totalTime = '00:00';
  jQuery.each(totalDurations, function(index, value) {
    var duration = moment.duration(value);
    totalTime = moment.duration(totalTime).add(duration);
  });
  alert(formatOutput(totalTime));
}

function formatOutput(result) {
  return result.hours() + ':' + result.minutes();
}

calculateTotalDuration();

Notice the reduced amount of code needed? You can even make the output more user-friendly with the humanize function, displaying '30 minutes' instead of '00:30'.

Answer №4

To properly calculate the total, make sure to convert the times to numbers first.

var total_durations = ['00:30', '01:30', '03:00', '04:30'];
var total = 0;
total_durations.forEach(function(value){
  var times = value.split(":");
  var number = parseInt(times[0],10) + parseInt(times[1],10)/60;
  total += number;
});

Now, convert total back to the time format (hh:mm).

var numString = String(total).split(".");
var displayTime = ("0" + String(numString[0])).slice(-2) + ":" + String(numString[1]*6);

DEMO

var total_durations = ['00:30', '01:30', '03:00', '04:30'];
var total = 0;
total_durations.forEach(function(value){
  var times = value.split(":");
  var number = parseInt(times[0],10) + parseInt(times[1],10)/60;
  total += number;
});

var numString = String(total).split(".");
var displayTime = ("0" + String(numString[0])).slice(-2) + ":" + String(numString[1]*6);

alert(displayTime);

Answer №5

Here is a straightforward functional solution in just one line:

let times = ['00:30', '01:30', '03:00', '04:30'],
    total = times.map(time => time.split(":").map(Number)).reduce((prev, current) => [prev[0] + current[0] + Math.floor((prev[1] + current[1]) / 60), (prev[1] + current[1]) % 60]);

document.write("<pre>" + total[0] + ":" + total[1] + "</pre>");

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

What is the best way to arrange an array or display it accurately?

Guys, here's a challenge for you: extract the values from this JSON data: [[name, brand, oem, category], [name, brand, oem, category], [name, brand, oem, category], [name, brand, oem, category]] Check out my JavaScript code: $(function(){ $('i ...

When the button is clicked, update the text within the <script> tags utilizing jQuery, JavaScript, or PHP

Here is the code snippet where changeme represents the text that needs to be replaced upon clicking a button: The following HTML and JavaScript code demonstrates this functionality: 1) Any input provided by the user in the field will be captured, replaci ...

After zooming in on the canvas and panning, I encountered a problem where I was unable to drag objects within the canvas. Instead, the canvas continued to pan as I tried to move the objects

1) I have the ability to pan the canvas and drag images without scaling or zooming. 2) When scaling or zooming, I can still drag images within the canvas. 3) However, if I try to pan the canvas after zooming and then attempt to drag images, only the canv ...

Enhancing React URLs

Our company deals with URLs in this format: http://helloworld.com/product?filter[category][0]=persian We aim to transform the URL into a cleaner version: http://helloworld.com/product-persian When additional filters are added to the current UR ...

Overlay a translucent image on top of another using JavaScript

Is it feasible to overlay a transparent-background image onto another image using JavaScript? For example, if you have a website featuring various product pictures and some of these products are recalled, can you superimpose the Do-Not-Enter sign (circle-w ...

Express.js application experiencing technical difficulties

When attempting to create a simple Express application with the file called serv.js, I encountered an error. Here is the code snippet I used: var express = require('express'), app = express(); app.listen(3000, function() { c ...

ways to parse a json file and apply a filter to find overlapping objects in nodejs

Looking for the top 5 games with the highest total playtime among users from a JSON file that contains game objects. Attempting to retrieve all objects by reading the file using the file system in Node.js: const queryGames = async () => { let data ...

Each time `fs.writeFile` is invoked, it initiates a fresh line

Every time this code is run, I want it to create a new line of data instead of overwriting the previous one. For example, if it's executed once, it would display: Checked Status: ONLINE. However, upon subsequent runs, it should add another line direc ...

Is it possible to incorporate numerous instances of SlickGrid by utilizing an angular directive?

Just started diving into AngularJS and it's been an exciting journey so far. I've come across the suggestion of wrapping external libraries into directories, which definitely seems like a good practice. While trying to create a 'slickgrid& ...

Sneaky spam and ads embedded within Joomla template

Today, while examining the source code of a Joomla site I am developing, I stumbled upon some hidden links that seem to be spam. I have spent an hour searching through various template files but have been unable to locate them. The hidden links in questio ...

Can we find a method to incorporate multicolored borders?

I currently have a td element with the following CSS styling: td { border-bottom: 3px solid aqua; } I want to be able to click on these cells and change their color, similar to the images linked below: https://i.sstatic.net/5DscU.png Is there a way ...

Add a class to alternate elements when mapping over data in React

Check out the code snippet below: <div className="grid md:grid-cols-2 sm:grid-cols-2 grid-cols-1 gap-16 mt-24 px-4"> {status === "success" && delve(data, "restaurants") && data.r ...

"Revamp the appearance of the div element upon clicking elsewhere on the

function replace( hide, show ) { document.getElementById(hide).style.display="none"; document.getElementById(show).style.display="flex"; } @import url('https://fonts.googleapis.com/css2?family=Allerta+Stenci ...

Using jQuery to manage multiple page requests on a single page

In my current project using Codeigniter, I encountered a challenge of loading multiple paginations on one page. After exploring various forums and websites, I decided to implement multiple methods and views to achieve this using jQuery. The code snippet I ...

Failure of Angular to execute HTTP calls asynchronously

I am feeling a bit perplexed about how and when to use the .then and/or .success functions. Here is a function example: $scope.handleData = function(option){ if(option == 1){ link = firstLink/; }else{ link = secondLink/; } ...

Did you manage to discover a foolproof method for the `filesystem:` URL protocol?

The article on hacks.mozilla.com discussing the FileSystem API highlights an interesting capability not previously mentioned. The specification introduces a new filesystem: URL scheme, enabling the loading of file contents stored using the FileSystem API. ...

What is the process of incorporating a lowercase normalizer into an Elasticsearch mapping object?

I'm attempting to incorporate a normalizer with a lowercase option into my mapping object, as detailed in the official Elasticsearch documentation Below is an example of my mapping object: const schema = { date: { type: 'date' ...

Manipulating and inserting objects into an array using React and Typescript with an undefined type

As I embark on my TypeScript journey in React, I decided to test my knowledge by creating a simple Todo App. Everything seems to be working fine except for one issue! After adding a new task and hovering over it, I received the following error message (tr ...

Modify the file format depending on the browser being used as Internet Explorer

Currently seeking the most effective method to dynamically alter the file extension of certain images (from .svg to .png) specifically for Internet Explorer users. Uncertain about the optimal approach: consider parsing the HTML code with PHP utilize jQu ...

Executing several API endpoint requests using an array in Node.js

Having difficulty utilizing values from an array to make API calls to endpoints. The array contains necessary data to retrieve the information needed from the endpoint. However, when attempting to parse the JSON text received from the API call and extract ...