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.
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.
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With