Simple Randomizer with Function Node & IF Node

You can easily build a simple randomizer node using Functions Node & IF Node.

Function Node generate a random number between 0-6\

If the number is smaller than 3 It’ll be True else it will be false.

Number
0
1
2
3 This is the center number between 0-6
4
5
6

Workflow Code:

2 Likes

Hey @mcnaveen!

Thank you for sharing this. Can you also share it on the workflows page? :slightly_smiling_face:

3 Likes

How can I do that bro?

If you haven’t, sign-up for the account, and you’ll see the option of Share New workflow. You can add a title, description as well as paste this workflow. :slightly_smiling_face:

1 Like

I’m not getting verification email. Could you please check? @jan

image

Did you check Spam folder, Promotions-Tab and searched for emails from “n8n”?

Yeah. Nothing arrived.

Can I do something similar to this but define random values to select from?
i.e. I have 6 ‘codes’, and I’d like to select one at random

Can you please explain what you mean exactly with “codes”? Can you maybe give an example.

Sorry @jan, by codes I meant random strings generated by me.
So for example, I have the following:
1234
1235
1236
1237
1238
1239
1240

These are actually staff ID’s which I’m using N8N to assign tickets and to - I’d like to use a script that randomly selects one of these so that the same person isn’t constantly bombarded with tickets. I hope that makes sense.

Then just one more question. Do you query this codes from somewhere and you so multiple items with one ID each or would you hard-code them somewhere?

Those codes never change, so I could use them directly in the function if easier. However, getting them from another http request would make it easier to manage should a new member of staff join. Each time the function gets run I’d like it to randomly select any one of those codes and serve it for the next node, rather than multiple items for each.

This seems to do the trick! I didn’t realise how simple the Function node was to include some js!

let StaffMembers = ['1234', '1235', '1236', '1237', 
'1238', '1239', '1240', '1241'];
let Staff = StaffMembers[Math.floor(Math.random() * StaffMembers.length)];
return Staff;
1 Like

Great to see that you found the answer yourself! Have fun!

Actually looking now at the code that would not work. You would have to change it slightly to return valid data.

So this would do the trick:

let staffMembers = ['1234', '1235', '1236', '1237', '1238', '1239', '1240', '1241'];
let staff = staffMembers[Math.floor(Math.random() * staffMembers.length)];
return [
  {
    json: {
      staff,
    }
  }
];
3 Likes

What would I do if I queried this data from somewhere?
I realized that through Edit JavaScript Code it is not possible to get information received in n8n