简体   繁体   中英

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

Use Array.prototype.filter:

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

Another solution with Array.filter():

names.map(
  (x) => x.name === 'Everything' && x.name
).filter(Boolean)

If you can use ES6, you can use generator for that:

Copy.names = Array.from(function* () {
    for (var x of rule.names) {
       if (x.name ==='Everything') {                                   
            // do nothing
       } else {
            yield x.name;
       }
    }
})

If not... you can always go for imperative way:

Copy.names = []

for (var x of rule.names) {
   if (x.name ==='Everything') {                                   
        // do nothing
   } else {
        Copy.names.push(x.name);
   }
}

If you can use Lodash (which I highly recommend), you can deal with it in elegant way by using _.flatMap :

Copy.names = _.flatMap(rule.names, function(x) {
    if (x.name ==='Everything') {                                   
        return [];
    } else {
        return [x.name];
    }
})

As you can see, it's similiar to map , except that you return array of items instead of item.

An answer I wrote elsewhere covers this, but if you want to be able to accomplish the transform of Array.map() but also to change the output length, you would need to use Array.reduce() .

Usually, though, it will make more sense to filter--preferably before you map, but if needed, then after.

For this you should use reduce instead of map, here an example:

Copy.names = rule.names.reduce(function (arr, x) {
  x.name !== 'Everything' && arr.push(x.name)
  return arr
}, [])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM