Home > OS >  Javascript search an array for a value starting with a certain value
Javascript search an array for a value starting with a certain value

Time:05-24

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??

CodePudding user response:

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

  • Related