Randomize members list order in for loops

When using for loops for away ghost modes, or party random lights most of the samples does not randomize the order of light switching.

A simple and quick way of randomizing the order of members in a group for use in a for loop is to replace the sortBy function with a random function.

B_All_Lights.members.sortBy[g|(Math::floor(Math::random*100))].forEach(light,i |
          logInfo("Vacation","Hello Light" + light)
      )

The above function will output the members of the B_All_Lights in a random order when called.

1 Like

Hello everyone, I can’t get the functionality to run under OH4.

I have already customized the whole thing a bit

  items.getItem('groupStatus').members.sortBy[g|(Math.floor(Math.random()*100))].forEach(function(item) {
    console.info(item.name + ', state : ' + item.state);
  })

but I get the following error message

2024-06-20 07:46:07.521 [ERROR] [b.automation.script.javascript.stack] - Failed to execute script:
org.graalvm.polyglot.PolyglotException: ReferenceError: "g" is not defined
	at <js>.:program(<eval>:138) ~[?:?]
	at org.graalvm.polyglot.Context.eval(Context.java:399) ~[?:?]

It works like this

let fLen = items.getItem('groupStatus').members.length;
let group = items.getItem('groupStatus').members;
console.info('random----------------------------------------------------------------------------------');
for (let i = fLen - 1; i > 0; i--) {
  const j = Math.floor(Math.random() * (i + 1));
  var temp = group[i];
  group[i] = group[j];
  group[j] = temp;
}  
  
 group.forEach(function(item) {
   console.info(item.name + ', state : ' + item.state);
  })

but the short form is of course much better.