Bar Chart programming help

#1

I am struggling to get the formatting correct for my bar chart. Sometimes, I do not have data for all 7 machines. I am having problems figuring out my loop in the function node. Here is what I have (no loop).

m.labels = ["Available Time",
            msg.payload[0].Machine,
            msg.payload[1].Machine,
            msg.payload[2].Machine,
            msg.payload[3].Machine,
            msg.payload[4].Machine,
            msg.payload[5].Machine,
            msg.payload[6].Machine];
m.data = [[480,
           (msg.payload[0].TotalTime/60).toFixed(2),
           (msg.payload[1].TotalTime/60).toFixed(2),
           (msg.payload[2].TotalTime/60).toFixed(2),
           (msg.payload[3].TotalTime/60).toFixed(2),
           (msg.payload[4].TotalTime/60).toFixed(2),
           (msg.payload[5].TotalTime/60).toFixed(2),
           (msg.payload[6].TotalTime/60).toFixed(2)]];
m.series = ["Total Time in 8 hours by Machine"];
return {payload:[m],topic:msg.topic};

This only works if all 7 of these have some data from the last 8 hours. Sometimes, there might only be 1 machine running.

How can I get this to loop properly?

Thanks,
Mike

#2

You can use

var arrayLength = msg.payload.length;
for (var i = 0; i < arrayLength; i++) {
   ...
}
#3

Thank you @Colin,

I should have posted my attempt of my for loop.
I had used a similar line in my attempt.

 for(var i = 0; i < msg.payload.length; i++) {
    ...
}

I think it is my placement, but I haven't had any luck. Here is my attempt with your suggestion, but I only get 1 machine.

var arrayLength = msg.payload.length;
for (var i = 0; i < arrayLength; i++) {
var m = {};
m.labels = ["Available Time",
            msg.payload[i].Machine];
m.data = [[480,
           (msg.payload[i].TotalTime/60).toFixed(2)]];
m.series = ["Total Time in 8 hours by Machine"];
return {payload:[m],topic:msg.topic};
}
#4

That is because you are returning at the end of the first pass so it doesn't get to do the rest. You need to build the arrays up. So declare the arrays just with the first (fixed) element

m.labels = ["Available Time"];
m.data = [[480]];

Then have your loop and use the Array.push() to add new items onto the array. So you will have something like

m.labels.push(msg.payload[i].Machine));
m.data[0].push((msg.payload[i].TotalTime/60).toFixed(2));
#5

Thank you @Colin!

var m = {};
m.labels = ["Available Time"];
m.data = [[480]];
m.series = ["Total Time in 8 hours by Machine"];
var arrayLength = msg.payload.length;
for (var i = 0; i < arrayLength; i++) {
    m.labels.push((msg.payload[i].Machine));
    m.data[0].push((msg.payload[i].TotalTime/60).toFixed(2));
}
return {payload:[m],topic:msg.topic};