Create array and randomize node.js array

103 Views Asked by At

I'm trying to write a cisco webex bot which get all people in the space(room) and randomly write only one name. I have this code

framework.hears("daily host", function (bot) {
  console.log("Choosing a daily host");
  responded = true;
  // Use the webex SDK to get the list of users in this space
  bot.webex.memberships.list({roomId: bot.room.id})
    .then((memberships) => {
      for (const member of memberships.items) {
        if (member.personId === bot.person.id) {
          // Skip myself!
          continue;
        }

        let names = (member.personDisplayName) ? member.personDisplayName : member.personEmail;
        let arrays = names.split('\n');
        var array = arrays[Math.floor(Math.random()*items.length)];
        console.log(array)
        bot.say(`Hello ${array}`);

       }
})
    .catch((e) => {
      console.error(`Call to sdk.memberships.get() failed: ${e.messages}`);
      bot.say('Hello everybody!');
    });
});

But this doesn't work. Also name after i use let arrays = names.split('\n'); separated by space and don't have comma. I think because of what code doesn't work Output of console log:

[ 'George Washington' ]

[ 'John' ]

[ 'William Howard Taft' ]

Main question now how to turn output to array?

2

There are 2 best solutions below

5
Rajsanthosh Sreenivasan On

That's because arrays[Math.floor(Math.random()*items.length)] only assigns an array with length 3. You need to randomise the index and push to array or use a sort function on the original array

 var array = arrays.sort((a,b)=>{
    return Math.floor(Math.random()*arrays.length);
 });

if you are looking to get the output as per you question you can use reduce instead of sort.

var arrays = [ 'George Washington', 'John',  'William Howard Taft'];
var array = arrays.reduce((a,i)=>{
    if(!a) a = [];
        a.splice(Math.floor(Math.random()*arrays.length), 0, [i]);
    return a;
 },[]);
6
JBS On

Here is how to get a single name from your data, and ensuring it is a string. There are only four names in the array, so run the snippet several times if you keep getting the same name.

// A list of names. Notice that Arraymond is an array; the other names are strings.
const names = [ 'George Washington', 'John',  'William Howard Taft', ['Arraymond'] ];

// Randomize the names
const randomNames = names.sort(() => Math.random() - 0.5);

// Get the first name. Make sure the name is a string (not an array)
const name = randomNames[0].toString();
 
console.log(name)

A tip: don't name your array "array" or "arrays" - it is not meaningful. Use good naming conventions and meaningful variable names that help others understand what the code is doing.