Click here to Skip to main content
15,868,024 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
This is some of the formattedResults (there are 60 results)

{
    "statusCode": "200",
    "time": "2022-12-07 10:24:00.000",
    "count": "3"
}


This is part of the code, seems to be an issue with the last line of code.

let labels = {}
let data
for (let index in formattedResults) {
    data = formattedResults[index]

    if (!labels[data.statusCode]) {
        labels[data.statusCode] = [...Array(61).keys()].map(i => 0)
    }

    labels[data.statusCode][(new Date(formattedResults.time).getTime() - 1670405100000) / 60000] = formattedResults.count
}


What I have tried:

When I try to run this in the console it says 'undefined', I'm expecting it to form a new array with all the different status codes and the counts for each minute.
Posted
Updated 14-Dec-22 3:29am

1 solution

Quote:
JavaScript
[...Array(61).keys()].map(i => 0)
That seems like a horribly inefficient method to produce a 61-element array of zeros. You create a new array, iterate over its keys, create a new array from that, then create a third array mapping each entry to zero.

You could simplify that to:
JavaScript
labels[data.statusCode] = Array(61).fill(0);
which only allocates a single array.

Quote:
JavaScript
(new Date(formattedResults.time).getTime() - 1670405100000) / 60000
Firstly, you're looking for a time property on the formattedResults array; you should be accessing the data variable instead.

Secondly, unless your time is always rounded to the nearest minute, that will return a floating-point number. If you want to use that as an index into your array, you need to round or truncate it.
JavaScript
Math.floor((new Date(data.time).getTime() - 1670405100000) / 60000)

You then have the same problem with the count - you're looking on formattedResults instead of data.

The fixed code:
JavaScript
let labels = {};
for (let index in formattedResults) {
    let data = formattedResults[index];

    if (!labels[data.statusCode]) {
        labels[data.statusCode] = Array(61).fill(0);
    }
	
	let s = Math.floor((new Date(data.time).getTime() - 1670405100000) / 60000);
    labels[data.statusCode][s] = data.count;
}
Demo[^]
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900