Reputation: 89
I want to filter an array with a function.
if (this.pendingItems.customer?.emailAddresses) {
this.pendingItems.customer.emailAddresses.filter(email => {
isEmailValid(email);
});
}
the function isEmailValid()
export function isEmailValid(s: string): boolean {
const re =
/^[a-z0-9+-][a-z0-9_+-]*(\.[a-z0-9_+-]+)*@([a-z0-9-]+\.)+[a-z0-9-]{2,}$/i;
return re.test(s);
}
return the correct response (true or false) with the emails([email protected] and test2email) I pass it, but the filter don't work.
Upvotes: 0
Views: 51
Reputation: 89
So the solution was:
if (this.pendingItems.customer?.emailAddresses) {
this.pendingItems.customer.emailAddresses = this.pendingItems.customer.emailAddresses.filter(isEmailValid);
}
I forgot to reassign the variable ;p
Upvotes: 0
Reputation: 15196
You need to modify your expression slightly. The method you pass to the filter function should return true/false but it always returns void (which will be cast to false).
filter(email => isEmailValid(email))
or
filter(isEmailValid)
or
filter(email => { return isEmailValid(email) })
In case you missed it - you forgot to return the result of the isEmailValid ;)
Upvotes: 1