Search code examples
node.jsif-statementreturn

nodejs map return nothing when if statement true


so i have the following code

data.push(commands.map(
    command => {
        if (!command.devOnly) { return command.name; } // first condition
        if (command.devOnly && message.author.id != '3251268789058714880') {} // second condition
    },
).join('\n'));

if the second condition is true it returns null but then when I run console.log(data) it has a blank line for all the commands where the second condition is true.

Is there a way to stop the second condition from returning anything, and not leaving the blank line


Solution

  • .map() is a 1-for-1 transformation so the output array will have EXACTLY the same number of elements in it as the input array. If you don't return anything, that element in the array will have an undefined value (which is the return value when you don't actively return something).

    To transform the array and eliminate some elements, you cannot use .map(). You can either do .filter().map() where you first filter out the items you don't want and then map the others or you can use a regular for loop and just push the items into output array that you want to keep using either a regular for loop iteration or a .reduce() or .forEach() iteration.

    One example:

    const results = commands.filter(command => !command.devOnly).map(command => command.name);
    console.log(results);
    
    const results = [];
    for (let command of commands) {
        if (!command.devOnly) results.push(command.name);
    }
    console.log(results);
    

    Note, your second condition doesn't do anything at all in your code example so I wasn't sure how to account for that in these examples.

    P.S. I've often wished Javascript had a .filterMap() feature that let you return undefined to leave that value out of the result - otherwise work like .map(). But, it doesn't have that feature built in. You could build your own.


    Per your comments, you can filter on two conditions like this:

    const results = commands
       .filter(command => !command.devOnly || message.author.id === '3251268789058714880')
       .map(command => command.name);
    console.log(results);