Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue.js search keyword in array

I am using Vue.js to filter items from a JSON array, using an input field. The array consists of mobile phones.

Looking at the Samsung array, I have Samsung Galaxy S5, Samsung Galaxy S6 etc.

Now when I type: Samsung, I get a list of all the samsungs. When I type Galaxy S5, I get the Samsung Galaxy S5. But when I type Samsung S5 I get nothing, because in between 'Samsung' and 'S5' there is 'Galaxy'.

I hope someone can help me out on this one.

My code:

<input type="text" v-model="keyword" class="form-control" id="telefoon" placeholder="Search...">


<script>
var app = new Vue({
  el: '#app',
  data: {
    keyword: '',
    samsungList: []
  },
  computed: {
    samsungFilteredList() {
      return this.samsungList.filter((samsung) => {
        return samsung.title.toLowerCase().includes(this.keyword.toLowerCase());
      });
    }
  }
});
</script>
like image 224
Mxkert Avatar asked Oct 27 '25 01:10

Mxkert


1 Answers

you can split your search keyword and check, if each word exists in title with every, which will return true, if each word will exist in title

var app = new Vue({
  el: '#app',
  data: {
    keyword: '',
    samsungList: []
  },
  computed: {
    samsungFilteredList() {
      return this.samsungList.filter((samsung) => {
        return this.keyword.toLowerCase().split(' ').every(v => samsung.title.toLowerCase().includes(v));
      });
    }
  }
});
like image 121
Artyom Amiryan Avatar answered Oct 28 '25 14:10

Artyom Amiryan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!