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

200
Visualizações
Higher Order Functions : Array Filter JavaSctipt

I have an array of strings that I am wanting to filter.

var words = ['hello', 'sunshine', 'apple', 'orange', 'pineapple'];

I am wanting to keep only the words that include the letter 'a'.

var wordsWithA = words.filter(function (word) {
  return words.indexOf('a', 4);
  
});

how do you accomplish this using indexOf in javascript?

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

indexOf returns -1, if it doesn't find the element in the container. You should use indexOf on each string word and not on the array words:

var words = ['hello', 'sunshine', 'apple', 'orange', 'pineapple'];

var wordsWithA = words.filter(function (word) {
  return word.indexOf('a') !== -1;
});

console.log(wordsWithA);

about 4 years ago · Juan Pablo Isaza Relatório

0

try

var words = ['hello', 'sunshine', 'apple', 'orange', 'pineapple'];
var wordsWithA = words.filter(function (word) {
  return word.indexOf('a') > -1;
  
});
about 4 years ago · Juan Pablo Isaza Relatório

0

String.prototype.indexOf(searchString, position) takes two arguments:

  1. First is the substring that needs to be searched.
  2. Second is an optional argument, that is the position from where the substring needs to be searched, the default value of which is 0.

And the method returns the index of the first occurrence of the searchString, if found, and returns -1 otherwise.

In your case you can omit the position argument and do it as follows:

const words = ["hello", "sunshine", "apple", "orange", "pineapple"],
  wordsWithA = words.filter((word) => word.indexOf("a") !== -1);

console.log(wordsWithA);

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