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

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

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 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