Home > Enterprise >  Listing an array in a message
Listing an array in a message

Time:04-06

I want to list an array in a discord message. I've got the following code so far:

message.channel.send("Game is starting with "   playerNumber   " Players! \n"
      memberIDs.forEach(element => ("<@"   element   "> \n")));

The memberIDs array contains all IDs from member in a specific channel, now I want to put all member who are in the channel into a message. I've tried it with the code above but it only gives me the message:

Game is starting with *playerNumber* Players!
undefined

I don't really understand why it is undefined because it also would give me the memberIDs in a console log or when I make a forEach loop with messages that get created for every memberID.

The Array in the console.log locks like the following:

[ '392776445375545355', '849388169614196737' ]

I appreciate any help.

CodePudding user response:

short answer
forEach() is not your friend; you need to map() and join()

long answer
the undefined is the result of the forEach() invocation which does not return anything.

so you need to get an string instead.

to do so, you may use .map() which returns an array; and .join() that joins an array of strings into an string.

something like this:

memberIDs.map(element => "<@"   element   ">" ).join('\n');

CodePudding user response:

forEach iterates over an array and doesn't return anything. Use map instead with join:

message.channel.send("Game is starting with "   playerNumber   " Players! \n"
      memberIDs.map(element => `<@${element}>`).join('\n')
);

CodePudding user response:

Array#map() returns an array of return values from the callback, while Array#forEach() returns undefined. Use .map()

memberIDs.map(m => `<@${m}>`)
.join("\n") // join each element with a newline

CodePudding user response:

forEach doesn't return anything in JavaScript, meaning that memberIDs.forEach(element => ("<@" element "> \n"))) will always be undefined.

let idString = "";

memberIDs.forEach(element => (idString = idString   "<@"   element   "> \n"))

message.channel.send("Game is starting with "   playerNumber   " Players! \n"
      idString);

What this code does is it defines a variable outside of the forEach loop, and then appends strings to it each time the loop runs.

  • Related