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.
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');
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')
);
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