1

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?

Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
Tri
  • 2,722
  • 5
  • 36
  • 65

3 Answers3

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"));
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
1

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)
Mark
  • 90,562
  • 7
  • 108
  • 148
0

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)

BlackBeard
  • 10,246
  • 7
  • 52
  • 62