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>
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));
});
}
}
});
Your requirement is partial search, For that includes
is not the correct method as it looks for exact match. You can use indexOf
let filteredResult = array.filter((i) => i.indexOf(this.keyword.toLowerCase()) > -1); // this will serve your purpose.
You can use "getMatchingResults()" method in your "samsungFilteredList " like below
var samsungList = ["Samsung Galaxy S5", "Samsung Galaxy S6"] function getMatchingResults(input) { return samsungList.filter(d => input.split(' ').every(v => d.toLowerCase().includes(v.toLowerCase()))) } console.log(getMatchingResults('samsung')) console.log(getMatchingResults('samsung s5')) console.log(getMatchingResults('galaxy'))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.