'Listing an array in a message

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.



Solution 1:[1]

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

Solution 2:[2]

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

Solution 3:[3]

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

Solution 4:[4]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Baboo
Solution 3 MrMythical
Solution 4 phqshy