UntitledGraphic
UntitledGraphic

Reputation: 1274

Filter out multiple text values from an array

I need to filter an array so that certain values don't get output if they contain a selection of words or phrases. For example, if my array goes something like ["John Smith", "Bob Smith", "John Doe", "Dave Jones"] I might want to exclude values that contain Bob or Dave.

Currently, to do this I have the following:

const filtered =
    names.filter(
        myArray.toLowerCase().indexOf('bob') === -1 
        && myArray.toLowerCase().indexOf('dave') === -1 
    ); 
let content = '';
filtered.forEach(item => {...}

This is great and it works, but If I was to increase the number of words to filter out this would become quite long-winded.

I thought I could get around this by using an array to filter by

myArray.toLowerCase().indexOf(['bob', 'dave']) === -1

This, as it turns out returns nothing at all. So went on to try

['bob', 'dave'].some(x => myArray.toLowerCase().indexOf(x) === -1)

but this also failed. I have an idea that the reason that these may be failing is that the logic is somehow looking for both values, but I've neither been able to prove that nor work out how to fix it.

Upvotes: 1

Views: 453

Answers (3)

Justin
Justin

Reputation: 2958

Adding on to @LaytonGB answer you can make it a function using the rest parameter

function filterNames(arr, ...arg) {
  let regex = new RegExp(arg.join("|"), "i");
  return arr.filter(n => !regex.test(n));
}

let arr = ["John Smith", "bOb Smith", "John Doe", "Dave Jones", "Mike Caw", "Arron Crybaby", "King George", "PaPa Murphy" ]
console.log(filterNames(arr, 'smith', 'Doe', 'mike', 'king'))

Upvotes: 0

Jiří Cihelka
Jiří Cihelka

Reputation: 378

You can check all the words with a for loop. A function for it could look something like this:

function filter(names, blacklist) {
    return names.filter(name => {
        for (const word of blacklist) {
            if (name.toLowerCase().includes(word.toLowerCase())) return false;
        }
        return true;
    });
}

Upvotes: 1

LaytonGB
LaytonGB

Reputation: 1404

Finding complex strings is easiest to do with Regex, which also has an in-built "ignore case" flag and can be assembled from a string array.

const names = ["John Smith", "Bob Smith", "John Doe", "Dave Jones"];
const exclude = ["bob", "dave"];
const excludeRegex = new RegExp(exclude.join("|"), "i"); // finds strings matching "bob" or "dave" ignoring case
const filtered = names.filter(n => !excludeRegex.test(n)); // Regexp.test(str) returns true if the search finds any matches in str
console.log(filtered)

Upvotes: 3

Related Questions