The mapAndFilter()
method allow a user to use both mecanism without chaining. Which means that he can either return a value that will be mapped, or return undefined
(e.g. omit return
statement) in which case the current object will be filtered out of the array.
Optionnally, you can also set the filter token to be something else with undefined
if you want your array to contain undefined
items.
const array = [
{ id: 1, filter: false },
{ id: 2, filter: false },
{ id: 3, filter: true },
{ id: 4, filter: true }
];
const result = array.mapAndFilter(function(e, i, a) {
if (e.filter) {
return { id:'#00' + e.id }
}
})
We get this result:
[{
"id": "#003"
}, {
"id": "#004"
}]