1

I have an array of strings that looks like this

arr = ['video-1', 'video-2', 'cpe-1', 'abc-1', 'abc-2']

I can simply filter this out by doing:

let newarr = arr.filter(item => item.indexOf('video') >= 0)

>> newarr = ["video-1", "video-2"]

However, I tried to use an array of strings as an input to give multiple filter options by doing

let q = ['video', 'CPE']
let newarr2 = arr.filter(item => q.indexOf(item) >= 0)

But this gives me an empty array. What is the correct usage?

2 Answers 2

2

Check whether .some of the keywords you want to include are included in the item.

Because the casing is different as well, call toLowerCase() on everything beforehand as well:

const arr = ['video-1', 'video-2', 'cpe-1', 'abc-1', 'abc-2'];
const keywordsToFind = ['video', 'CPE'];
const keywordsToFindLower = keywordsToFind.map(s => s.toLowerCase());
const newarr2 = arr.filter(
  item => keywordsToFindLower.some(
    keywordToFind => item.toLowerCase().includes(keywordToFind)
  )
);
console.log(newarr2);

Sign up to request clarification or add additional context in comments.

Comments

1

You can make a regex from q to make this more efficient than using other array methods:

const arr = ['video-1', 'video-2', 'cpe-1', 'abc-1', 'abc-2'];
const q = ['video', 'CPE'];

const re = RegExp(q.join("|"), "i");
const res = arr.filter(e => re.test(e));

console.log(res);

1 Comment

While valid for the requirements of the question, this solution assumes that none of the strings in q contain any RegEx characters. For example, in this (hastily thrown together) case, the "c" and the "e" are returned by the filter, when they shouldn't be.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.