Santhosh
Santhosh

Reputation: 53

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";
        }
    }
}

Upvotes: 1

Views: 228

Answers (1)

async await
async await

Reputation: 2405

👋 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";
        }
    });
}

Upvotes: 1

Related Questions