I have a questions base on previous questions here.
There I'm using Python to do that, but now I want to convert the code to Javascript code.
So basically my questions there are, let's say I have an array like this:
job_list = ['assistant manager', 'salesperson', 'doctor', 'production manager', 'sales manager', 'schoolteacher', 'mathematics teacher']
And now I want to search with multiple keywords in my array, e.g:
When I try to input the keyword teacher and sales, it should return result like this:
- schoolteacher
- mathematics teacher
- salesperson
- sales manager
So, how to do that in Javascript?
3 Answers 3
Use filter and some:
const job_list = ['assistant manager', 'salesperson', 'doctor', 'production manager', 'sales manager', 'schoolteacher', 'mathematics teacher'];
const getJobs = (...words) => job_list.filter(s => words.some(w => s.includes(w)))
console.log(getJobs("teacher", "sales"));
Comments
You can make a regular expression that describes what you want and filter accordingly with test():
let job_list = ['assistant manager', 'salesperson', 'doctor', 'production manager', 'sales manager', 'schoolteacher', 'mathematics teacher']
let filtered = job_list.filter(job => /teacher|sales/.test(job))
console.log(filtered)
Comments
You can use filter like this:
job_list = ['assistant manager', 'salesperson', 'doctor', 'production manager', 'sales manager', 'schoolteacher', 'mathematics teacher']
console.log(job_list.filter(word => word.includes("teacher") || word.includes("sales")))
Complexity: O(N)