2-dimensional arrays

Hi,
i try to generate a 2 dimensional arrya (10 rows, 20 columns) and initialize them with data within nested for loops.
My problem is: i cannot find the correct syntax to get it working. www.w3schools.com has no example for those arrays. The only thing i found is var person = [];

So i tried:

var state = [[],[]];

for (device = 1;device < 11;device++) {
    for (index = 0; index < 20; index++) {
        state[device][index] = 0;
    }
}
flow.set("state",state);

but i get "TypeError: Cannot set property '0' of undefined"

Would be happy if anyone has a good hint for me!

1 Like

You need to create an array of arrays... here is a simple flow to demonstrate

[{"id":"c30c7879.98d578","type":"inject","z":"eeee575.b4b80a8","name":"","props":[{"p":"payload"},{"p":"topic","vt":"str"}],"repeat":"","crontab":"","once":false,"onceDelay":0.1,"topic":"","payload":"","payloadType":"date","x":90,"y":580,"wires":[["707bb032.ac3e9"]]},{"id":"707bb032.ac3e9","type":"function","z":"eeee575.b4b80a8","name":"","func":"var arr = [];\nfor(var r = 0; r < 10; r++) { // for each of 10 rows\n    arr[r] = [];    \n    for(var c = 0; c < 20; c++) {  // create 20 columns\n        arr[r][c] = (r+1)*(c+1);     // with some value in\n    }    \n}\nmsg.payload = arr; // return the array\nreturn msg;","outputs":1,"noerr":0,"initialize":"","finalize":"","x":240,"y":580,"wires":[["38f6b117.c94b3e"]]},{"id":"38f6b117.c94b3e","type":"debug","z":"eeee575.b4b80a8","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"false","statusVal":"","statusType":"auto","x":410,"y":580,"wires":[]}]

Good morning,
looks quite different to my approach ...
Of course, this solution works fine.
Where can i find infos like this? w3school seems not to be the best solution.

Thx and kind regards,
Alexander

A Google search for "js 2 dimensional array" provides lots of answers. In situations like these, I just search search search, try try try and eventually I find the answer. This also has a positive effect... I learn more.

5 Likes

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.