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

112
Vistas
How to change the for loop into filter method?

I have created the menu cards using the inputs from the user. In the cards , I want to filter the cards by using their dish name and display = 'none' the other cards. The filtering should happen when the filter button is clicked. My code is below. I iterated the cards using for loop. But i want to do it by filter method and without using for loop.

const breakfastBtn = document.querySelector('.breakfast-btn');

breakfastBtn.addEventListener('click', filterBreakFast);

function filterBreakFast(){
    let type = cardsContainer.querySelectorAll('.card-length')
  
    for ( let i = 0; i < type.length; i++ ) {
        let span = type[i].querySelector('.card-dish-type');
        if ( span.innerHTML.indexOf('Brunch') > -1 ) {
            type[i].style.display = "initial";
        } else {
            type[i].style.display = "none";
        }
    }
}
about 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

👋 For already working code that you would like to be reviewed, you might find a better response at code review.

If your only intention is to avoid using a for loop, this is an example of your code rewritten with array methods. The .filter method is probably not what you're looking for in this instance. .filter returns another array filtered based on a function. What it seems you intend to do is apply two different actions based on whether or not the html of an element includes the string "Brunch".

We can use the .forEach array method instead of a for... in loop, though it's mostly a stylistic change.

const breakfastBtn = document.querySelector('.breakfast-btn');

breakfastBtn.addEventListener('click', filterBreakFast);

function filterBreakFast() {
    const type = cardsContainer.querySelectorAll('.card-length');
    type.forEach(element => {
        const span = element.querySelector(".card-dish-type");
        const hasBrunch = span.innerHTML.includes("Brunch");
        if (hasBrunch) { 
            element.style.display = "initial";
        } else { 
            element.style.display = "none";
        }
    });
}
about 4 years ago · Santiago Trujillo 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