Random number from 0 to max of array number

i found this node geting some quotes and then send it as Telegram
i have done something similar. but need help for the Random function!

it is "hardcoded" like this
msg.payload = msg.payload[getRndInteger(0,1642)];

but if i do the http request i would get a array[1643] information
how to i have to change the function-node to get a random number between 0 and the max array?

[{"id":"f04fd779.cea4c8","type":"inject","z":"ac8d9bb9.eb8a58","name":"At 11:00am","props":[{"p":"payload"},{"p":"topic","vt":"str"}],"repeat":"","crontab":"00 11 * * *","once":false,"onceDelay":"","topic":"","payload":"","payloadType":"date","x":170,"y":1380,"wires":[["b031a18e.59b03"]]},{"id":"b031a18e.59b03","type":"http request","z":"ac8d9bb9.eb8a58","name":"","method":"GET","ret":"obj","paytoqs":"ignore","url":"https://type.fit/api/quotes","tls":"","persist":false,"proxy":"","authType":"","x":370,"y":1380,"wires":[["e6a4d14d.ce6a8","348b01d6.0271de"]]},{"id":"e6a4d14d.ce6a8","type":"function","z":"ac8d9bb9.eb8a58","name":"","func":"msg.payload = msg.payload[getRndInteger(0,1642)];\nreturn msg;\n\n// this code gets a random interger\nfunction getRndInteger(min, max) {\n    return Math.floor(Math.random() * (max - min + 1) ) + min;\n}","outputs":1,"noerr":0,"initialize":"","finalize":"","x":560,"y":1380,"wires":[["94bfd95f.2c89a8","353a40d8.ac2ca"]]},{"id":"348b01d6.0271de","type":"debug","z":"ac8d9bb9.eb8a58","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"false","statusVal":"","statusType":"auto","x":620,"y":1240,"wires":[]}]

Use array.length-1 instead of the hard coded value.

like this
msg.payload = msg.payload[getRndInteger(0,array.length-1)];

seems to be wrong, i mean i don't get any message anymore

Do you have an array variable named array?

When I said Use array.length-1 you are supposed to use your array variable eg myArray.length.

(I'm on my phone so can't load your flow)

it has no name just
msg.payload : array[1643]
and below all the information

Sure it does. All variables have a name.

According to that ^ your array is a property member of the msg object named payload

So msg.payload.length will be what you use.

add this like that

msg.payload = msg.payload[getRndInteger(0,msg.payload.length)];

and yes it seems to work

You forgot to add the -1 .. and in some very rare occusion you may get a random number outside the length of the array that starts from 0.

So as Steve suggested
msg.payload = msg.payload[getRndInteger(0, msg.payload.length - 1 )];

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