Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can we filter elements in array with regex in array with javascript?

Let's say I have two arrays: one is the regex and the other one is the input. What, then, is the best way - in terms of performance and readability - to do something like the output?

var regex = [
    '/rat/',
    '/cat/'
    '/dog/',
    '/[1-9]/'
]

var texts = [
    'the dog is hiding',
    'cat',
    'human',
    '1'
]

the end result is

result = [
    'human'
]

Well, what I was thinking was to do something like reduce:

// loop by text
for (var i = texts.length - 1; i >= 0; i--) {
    // loop by regex
    texts[i] = regex.reduce(function (previousValue, currentValue) {
        var filterbyRegex = new RegExp("\\b" + currentValue + "\\b", "g");  
        if (previousValue.toLowerCase().match(filterbyRegex)) {
            delete texts[i];
        };
        return previousValue;
    }, texts[i]);
}

But, is that not readable? Maybe there is another way that I haven't thought of.

like image 608
user1780413 Avatar asked Oct 28 '12 07:10

user1780413


People also ask

How do you filter an array in JavaScript?

One can use filter() function in JavaScript to filter the object array based on attributes. The filter() function will return a new array containing all the array elements that pass the given condition. If no elements pass the condition it returns an empty array.

How can we filter an array of elements from a given array in ES6?

ES6 | Array filter() Method Callback: The function is a predicate, to test each element of the array. Return true to keep the element, false otherwise. It accepts three arguments: element: The current element being processed in the array.

What is regex filtering?

The Regex Filter transform filters messages in the data stream according to a regular expression (regex) pattern, which you can define. You also define the Regex Filter to either accept or deny incoming messages based on the regular expression.


1 Answers

I would probably go something like this

var regexs = [
    /rat/i,
    /cat/i,
    /dog/i,
    /[1-9]/i
]

var texts = [
    'the dog is hiding',
    'cat',
    'human',
    '1'
]

var goodStuff = texts.filter(function (text) {
    return !regexs.some(function (regex) {
         return regex.test(text);
    });
});

But realistically, performance differences are so negligible here unless you are doing it 10,000 times.

Please note that this uses ES5 methods, which are easily shimmable (I made up a word I know)

like image 95
Roderick Obrist Avatar answered Sep 21 '22 00:09

Roderick Obrist