简体   繁体   中英

Add array of HH:MM:SS values in node.js

I have array of time values as.

var time = [
    "03:05:11",
    "00:00:12",
    "03:03:14"
]

How do I add all the array values such that I get the output as "06:08:37" (sum of "03:05:11" + "00:00:12" + "03:03:14" ).

If there are N no of array values, how do we do it without looping in node.js ?

Sounds like a job for moment.js ( http://momentjs.com/ )

First we'll need to parse time spans into something usable for calculations using moment.duration constructor and then we use an array reduce to sum up these values:

var moment = require('moment');
var sum = [
  "03:05:11",
  "00:00:12",
  "03:03:14"
].map(t => moment.duration(t))
.reduce((sum, current) => sum.add(current), moment.duration());

For formatting sum to a "hh:mm:ss" format the moment-duration-format plugin could be used ( https://github.com/jsmreese/moment-duration-format ):

console.log(sum.format("hh:mm:ss"));

This answer requires looping as all answers will since data is stored in an array.

Hand babelified ES5 version

var sum = [
  "03:05:11",
  "00:00:12",
  "03:03:14"
].map(function(t) { return moment.duration(t); })
.reduce(function(sum, current) { return sum.add(current); }, moment.duration());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM