In my project, I am working with two files: index.js and list.json.
My goal is to extract an element from list.json and insert it into a nested array following the structure [hour][visits per hour].
The hour refers to the index of the hour; for example, hour 12 corresponds to index 12. However, I keep encountering undefined errors in the console. Below, I will include a snippet to illustrate this issue.
Here is a sample from the json file, consisting of a total of 28 lines:
[
{ "time":"01:34:19", "visits": 37 },
{ "time":"02:03:21", "visits": 42 },
{ "time":"02:22:35", "visits": 51 },
{ "time":"02:43:54", "visits": 31 },
{ "time":"03:31:43", "visits": 24 },
{ "time":"03:38:01", "visits": 27 },
{ "time":"05:29:57", "visits": 36 },
{ "time":"05:54:08", "visits": 47 },
{ "time":"06:11:17", "visits": 49 },
{ "time":"07:22:03", "visits": 51 },
{ "time":"07:27:09", "visits": 55 },
]
Below is the JavaScript code attempt:
let json = require('./list.json');
let visitsPerHr = [];
visitsPerHr.length = 24;
//To prevent type error in the second loop
for (let x = 0; x < 24; x++) {
visitsPerHr[x] = x;
}
let hour = -1;
let visitCount = -1;
for(let i = 0; i < json.length; i++){
//Extracting and parsing hour
hour = json[i].time[0] + json[i].time[1];
hour = parseInt(hour, 10);
//Extracting and parsing visits
visitCount = json[i].visits;
visitCount = parseInt(visitCount, 10);
//Adding visitCount to the relevant hour index
visitsPerHr[hour].push = visitCount;
}
I need assistance with correctly assigning visitCount to the corresponding hour index. As I iterate through each index (from hours 1 to 23), I should be able to retrieve all the visits for that particular hour.
An ideal outcome for hour 7 would look like this: [7][27,29,22]
However, the current result displays as follows:
2
undefined
2
undefined
2
undefined
2
undefined
5
undefined
6
undefined
6
undefined
6
undefined
6
undefined
7
undefined
7
undefined
7
undefined
7
undefined
7
undefined
8
undefined
9
undefined
10
This pattern continues until reaching hour 23.