Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

119
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda