Estoy buscando una forma de buscar una matriz para ver si hay un valor presente que comience con el término de búsqueda.
const array1 = ['abc','xyz'];Entonces, una búsqueda de 'abcd' devolvería verdadero en lo anterior.
He estado jugando con las inclusiones, pero eso solo parece verificar el valor total. Además, ¿comienza con? No creo que funcione, ya que creo que verifica una cadena y no valores en una matriz.
Puede usar la función find() que le permite pasar una función personalizada en el parámetro que se probará en cada valor. De esta manera, puede usar startsWith() en cada valor de la matriz como pretendía.
Ejemplo:
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 Si desea devolver true o false en lugar del valor, puede verificar si el valor devuelto es diferente de undefined .
function findStartWith(arg) { return !!array1.find(value => { return arg.startsWith(value); }) !== undefined; }El mismo fragmento con un booleano:
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