Search code examples
javascriptarraysarray-map

how to return nothing ( empty array) with array.map function


Right now, if 'Everything' in the list is detected, the output becomes [""].
Expected output: []

Copy.names = rule.names.map(function(x) {                                
    if (x.name ==='Everything') {                                   
        return '';
    } else {
        return x.name;
    }
});

Solution

  • Use Array.prototype.filter:

    Copy.names = rule.names.filter(function(x) {                                
        return x.name !=='Everything';
    }).map(function (x) {
        return x.name;
    });