Octane
Octane

Reputation: 198

Filter list of array with regex

I'm trying to filter this

Alert me when this account’s current balance goes above $1.

from the list here:

alertTypes = [
 'Alert me when this account’s available balance goes below $1.',
 'Alert me when this account’s current balance goes below $1.',
 'Alert me when this account’s available balance goes above $1.',
 'Alert me when this account’s current balance goes above $1.']

Using this async function

const alertRegEx = "/.*current balance.*above.*/"
const alert = alertTypes.filter(alert => alert.match(alertRegEx))

But im getting the whole list in alert variable. What's my mistake here?

Upvotes: 0

Views: 128

Answers (1)

Gabriele Petrioli
Gabriele Petrioli

Reputation: 195992

Firstly, do not use async in this case as match is not an async function (but even if it was you would not be able to use it in a filter). Then you need to use an literal regular expression,not a string.

And a minor, non-required, change is that you can skip the initial and final .*

const alertTypes = [
 'Alert me when this account’s available balance goes below $1.',
 'Alert me when this account’s current balance goes below $1.',
 'Alert me when this account’s available balance goes above $1.',
 'Alert me when this account’s current balance goes above $1.']



const alertRegEx = /current balance.*above/;
const alerts = alertTypes.filter( alert =>  alert.match(alertRegEx))

console.log(alerts);

Upvotes: 2

Related Questions