Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VueJS2: How to check if array contains specific elements?

I have a Vue application with a series of checkboxes that add items to an array when the user selects a checkbox. There are about 6 items that could be selected, however, I need to reveal a <div> if 2 specific items are selected:

Example array if all elements are checked:

["Apples", "Bananas", "Cucumbers", "Pears", "Peaches", "Strawberries"]

But, if ONLY Apples and Pears are checked AND/OR if Apples OR Pears are checked, I need to reveal a div in the view with a set of instructions for the user.

I tried this but it didn't work:

<div v-if="(selectedProducts.length <= 2) && ( selectedProducts.includes('Apples') || selectedProducts.includes('Pears') )">
...show mycontent...
</div>

In my vue instance I have initiated the data like so:

data: {
    selectedProducts: []
}

What's the correct way to write this logic? Should I use the array.every() method in this case? Thank you.

like image 452
redshift Avatar asked Sep 13 '17 17:09

redshift


2 Answers

You could try

selectedProducts.indexOf('Apples') !== -1

Instead of

selectedProducts.includes('Apples')
like image 106
VOL Avatar answered Oct 15 '22 07:10

VOL


If I understand correctly, you want to show the DIV if both apples and pears are selected and only two items are selected, or if one item is selected and the product is either apples or pears.

If that's true, here is a computed that does that.

computed:{
  matched(){
    let pears = this.selectedProducts.includes("Pears")
    let apples = this.selectedProducts.includes("Apples")
    if (this.selectedProducts.length === 2 && pears && apples) return true
    if (this.selectedProducts.length === 1 && (apples || pears)) return true
    return false
  }
}

Working Example:

console.clear()

new Vue({
  el: "#app",
  data:{
    products: ["Apples", "Bananas", "Cucumbers", "Pears", "Peaches", "Strawberries"],
    selectedProducts: []
  },
  methods:{
    onChange(evt, product){
      if (evt.target.checked){
        this.selectedProducts.push(product)
      } else {
        this.selectedProducts.splice(this.selectedProducts.indexOf(product), 1)
      }
    }
  },
  computed:{
    matched(){
      let pears = this.selectedProducts.includes("Pears")
      let apples = this.selectedProducts.includes("Apples")
      if (this.selectedProducts.length === 2 && pears && apples) return true
      if (this.selectedProducts.length === 1 && (apples || pears)) return true
      return false
    }
  }
})
<script src="https://unpkg.com/[email protected]"></script>
<div id="app">
  <div v-for="product in products">
    <label for=""><input type="checkbox" :value="product" @change="onChange($event, product)"> {{product}}</label>
  </div>
  {{selectedProducts}}
  
  <hr>
  <div v-if="matched">
    Matched Criteria
  </div>
</div>
like image 27
Bert Avatar answered Oct 15 '22 09:10

Bert