0

I'm having an array of milliseconds which I want a total of. I have tried the array.reduce and use a for-loop but all I get is total gibberish when I console it or use on the site. If I get the milliseconds summed up I could convert them to seconds and, if needed, minutes.

Code:

window.timeArray = [2493, 2109, 4424, 1971, 3411, 1834, 2418]

let totalTimeSum = 0
for (let i = 0; i < window.timeArray.length; i++) {
  totalTimeSum += parseInt(window.timeArray[i])
}
document.querySelector('#score').innerText += totalTimeSum  
// 1866018660, should be 15249 - 15 sec 249 millisec

Optional code:

let totalTime = (sum, value) => sum + value
let totalTimeSum = window.timeArray.reduce(totalTime)
document.querySelector('#score').innerText += totalTimeSum  
// 1866018660, should be 15249 - 15 sec 249 millisec
Thomas Bengtsson
  • 399
  • 2
  • 10
  • 22

1 Answers1

4

In order to accomplish what you need, you can do the following:

  1. You can use Array.prototype.reduce to calculate the sum of the array's elements.

  2. Then, to calculate the number of seconds, round down the quotient of the sum divided by 1000.

  3. The remainder is the number of milliseconds remaining.

Snippet:

var
  /* Define the array. */
  timeArray = [2493, 2109, 4424, 1971, 3411, 1834, 2418],
  
  /* Calculate the sum. */
  sum = timeArray.reduce((previous, current) => previous + current, 0),
  
  /* Calculate the seconds. */
  seconds = Math.floor(sum / 1000),
  
  /* Calculate the milliseconds. */
  milliseconds = sum % 1000;

/* Set the value as text to the score element. */
document.querySelector("#score").innerText = seconds + "s " + milliseconds + "ms";
<div id = "score"></div>
Angel Politis
  • 10,955
  • 14
  • 48
  • 66