Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sum time string in an array?

Suppose, I've an array of different time string.

let a: any = ["7:20", "5:50", "6:30"];

I want to sum up these HH:mm time strings. I am building up an app using Ionic 4 (Angular). I have already used momentjs for these. But, unfortunately yet I can't find any solution.

Update: Expected Result: 7:20 + 5:50 + 6:30 = 19:40 (HH:33)

like image 614
Abhijit Mondal Abhi Avatar asked Jan 23 '19 08:01

Abhijit Mondal Abhi


People also ask

How do you find the sum of items in an array?

You can find the sum of all elements in an array by following the approach below: Initialize a variable sum to store the total sum of all elements of the array. Traverse the array and add each element of the array with the sum variable. Finally, return the sum variable.

How to reduce array of objects in JavaScript?

The array reduce in JavaScript is a predefined method used to reduce an array to a single value by passing a callback function on each element of the array. It accepts a function executed on all the items of the specified array in the left-to-right sequence. The returned single value is stored in the accumulator.


1 Answers

You can treat time as moment durations that can be summed up:

const any = ['7:20', '7:52', '5:03', '1:01', '9:02', '6:00'];

const sum = any.reduce((acc, time) => acc.add(moment.duration(time)), moment.duration());

console.log([Math.floor(sum.asHours()), sum.minutes()].join(':'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.23.0/moment.min.js"></script>
like image 167
antonku Avatar answered Sep 24 '22 07:09

antonku