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

152
Vistas
How to search some text in an array and get the index of the searched array in javascript

I want to get the index of filtered array

const arr = ['apple', 'mango', 'orange', 'banana'];

const customFilter = (arr, searchtxt) => {
  const result = [];
  arr.filter(fruit => fruit.match(searchtxt)).forEach((element, index) => {
    result.push(index);
  });
  return result;
}

console.log(customFilter(arr, 'ma'));

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

You can use reduce. For each item in the input, the code below adds its index to an array if it matches the given string.

const arr = ['apple', 'mango', 'orange', 'banana'];

const customFilter = (arr, searchtxt) => {
  return arr.reduce((a, c, i) => c.match(searchtxt) ? [...a, i] : a, [])
}

console.log(customFilter(arr, 'ma'));

about 4 years ago · Juan Pablo Isaza Denunciar

0

You're returning the index in the filtered array, not its index in the original array.

Don't use filter() for this. Just use forEach(), pushing the index into the result.

const arr = ['apple', 'mango', 'orange', 'banana'];

const customFilter = (arr, searchtxt) => {
  const result = [];
  arr.forEach((fruit, index) => {
    if (fruit.match(searchtxt)) {
      result.push(index);
    }
  })
  return result;
}

console.log(customFilter(arr, 'ma'));

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