If the query value, or part of the query value, is in the array, return true

68 views Asked by At

I have an employee list containing over 600 names (first- and last name). Based on this list, I need to create an array. I also need a syntax that, based on search queries, browse through this array and returns either true or false if the search query string is part of the array. The Search query is already captured in a variable called query.

Example:

  1. Array

    var employee = [ "John Smith", "Bob Hope", "Scott John", "Calum John" ];

  2. If the query value, or part of the query value, is in the array employee, return true, otherwise, return false

Example:

  • If query equals john smith, return true
  • If query equals bob, return true
  • If query equals SCOTT JOHN FINANCE DEPARTMENT, equals true
  • If query equals health insurance, equals false

So basically, if the search query contains any name, return true.

Hope this is clear enough. JavaScript is not my prime, so really appreciate all help I can get.

Best, John

1

There are 1 answers

8
Hassan Imam On

You can use array#some with array#includes by converting your query to lowercase as well as converting the employee name to lowercase.

employees.some(employee => employee.toLowerCase().includes(query.toLowerCase()) || query.toLowerCase().includes(employee.toLowerCase()))

var employees = [ "John Smith", "Bob Hope", "Scott John", "Calum John" ],
    queries = ['john smith', 'bob', 'SCOTT JOHN FINANCE DEPARTMENT', 'health insurance'],
    result = queries.map(query => employees.some(employee => employee.toLowerCase().includes(query.toLowerCase()) || query.toLowerCase().includes(employee.toLowerCase())));
console.log(result);