Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

111
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!