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?

Adam Baser
  • 115
  • 7
  • 2
    Seems you should just be `map()` ing your array to render the elements. – pilchard Jan 22 '21 at 11:03
  • And before the `map` the array can be filtered using `filter` – evolutionxbox Jan 22 '21 at 11:05
  • Does this answer your question? [filtering an array of objects based on another array in javascript](https://stackoverflow.com/questions/46894352/filtering-an-array-of-objects-based-on-another-array-in-javascript) – evolutionxbox Jan 22 '21 at 11:06
  • Set Data Structure Can works for you . [Reference](https://stackoverflow.com/questions/31930894/javascript-set-data-structure-intersect) – tamil Jan 22 '21 at 11:17

1 Answers1

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.

Beni Trainor
  • 346
  • 1
  • 11