Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

201
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda