0

So i have this array as my state:

["item-one","item-two", "item-three"] 

Now i have these items on my webpage:

Item One Item Two Item Three Item Four Item Five 

How can i filter these items based on the state of my array. So when i filter i would get the three first items? The html of the items are like so.

 <div> <label htmlFor="item-one">Item One</label> <input type="checkbox" name="" id="item-one"/> </div> <div> <label htmlFor="item-two">Item Two</label> <input type="checkbox" name="" id="item-two"/> </div> <div> <label htmlFor="item-three">Item Three</label> <input type="checkbox" name="" id="item-three"/> </div> <div> <label htmlFor="item-four">Item Four</label> <input type="checkbox" name="" id="item-four"/> </div> <div> <label htmlFor="item-five">Item Five</label> <input type="checkbox" name="" id="item-five"/> </div> 

should i use a map function or what is the best approach?

4
  • 2
    Seems you should just be map() ing your array to render the elements. Commented Jan 22, 2021 at 11:03
  • And before the map the array can be filtered using filter Commented Jan 22, 2021 at 11:05
  • Does this answer your question? filtering an array of objects based on another array in javascript Commented Jan 22, 2021 at 11:06
  • Set Data Structure Can works for you . Reference Commented Jan 22, 2021 at 11:17

1 Answer 1

0

You would need a reference to those elements on the page. From there, in you're render function you would show/hide those elements based on you're state.

Example:

// Assume `this.state` references you're array const items = document.querySelector("div"); items.forEach(function (item) { const input_elm = item.querySelector("input"); if (this.state.includes(input_elm.id)) { item.style.display = "block"; } else { item.style.display = "none"; } }); 

Note: there are other ways to implement this. But I found this to be the simplest.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.