Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

117
Views
Javascript search an array for a value starting with a certain value

I am looking for a way to search an array to see if a value is present that starts with the search term.

const array1 = ['abc','xyz'];

So a search for 'abcd' would return true on the above.

I have been playing about with includes, but that only seems to check the full value. Also, startsWith I dont think will work as I believe that checks a string and not values in an array??

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You can use the find() function which allows you to pass a custom function in parameter that will be tested on each value. This way you can use startsWith() on each value of the array as you intended to do.

Example:

const array1 = ['abc','xyz'];

function findStartWith(arg) {
  return array1.find(value => {
    return arg.startsWith(value);
  });
}

console.log(findStartWith("hello")); // undefined
console.log(findStartWith("abcd")); // abc
console.log(findStartWith("xyzz")); // xyz

If you want to return true or false instead of the value, you can check if the returned value is different from undefined.

function findStartWith(arg) {
  return !!array1.find(value => {
    return arg.startsWith(value);
  }) !== undefined;
}

The same snippet with a boolean:

const array1 = ['abc','xyz'];

function findStartWith(arg) {
  return array1.find(value => {
    return arg.startsWith(value);
  }) !== undefined;
}

console.log(findStartWith("hello")); // false
console.log(findStartWith("abcd")); // true
console.log(findStartWith("xyzz")); // true

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!