4

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>

3 Answers 3

10

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));
      });
    }
  }
});
Sign up to request clarification or add additional context in comments.

Comments

4

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.

1 Comment

Thanks for the response. I used Artyom's solution, but will still look into yours.
1

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'))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.