how to return nothing ( empty array) with array.map function
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.
Another solution with Array.filter():
names.map(
(x) => x.name === 'Everything' && x.name
).filter(Boolean)
Use Array.prototype.filter:
Copy.names = rule.names.filter(function(x) {
return x.name !=='Everything';
}).map(function (x) {
return x.name;
});