Home > Mobile >  Searching for numbers in an array - js
Searching for numbers in an array - js

Time:11-02

The search is working properly. The main problem occurs when I want to delete it but the previous numbers won't be back. In this code, I'm applying the changes directly to the main variable but I shall not. What is the way?

new Vue({
  el: '#app',
  data() {
    return {
      list: [],
      search: '',
    }
  },
  mounted() {
    for(let i = 1300; i <= 1400; i  ) {
      const _n = i.toString()
      this.list.push(_n)
    }
  },
  methods: {
    handleSearch() {
      this.list = this.list.filter(i => i.includes(this.search));
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <input @input="handleSearch()" v-model="search" placeholder="search number" />
  <ul>
    <li v-for="(item, i) in list" :key="i">{{item}}</li>
  </ul>
</div>

CodePudding user response:

The issue happens because you nested filter the same list, but you need to have a list with full items and another list with filtered items, and iterate on the filtered items, not the main list.

I suggest you use computed property with the filtered list, instead of firing input event because you already use v-model to control the input

new Vue({
  el: '#app',
  data() {
    return {
      list: [],
      search: '',
    }
  },
  mounted() {
    for(let i = 1300; i <= 1400; i  ) {
      const _n = i.toString()
      this.list.push(_n)
    }
  },
  computed: {
    filteredList() {
      return this.list.filter(i => i.includes(this.search));
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <input v-model="search" placeholder="search number" />
  <ul>
    <li v-for="(item, i) in filteredList" :key="i">{{item}}</li>
  </ul>
</div>

CodePudding user response:

YOu have list where you filter the items and overwrite list with the new filtered result.

When you move a char, you apply same same on list, but those items were already removed right? No way to get them back.

Use a second list, originalList that you will use to filter, but do not overwrite so you can always refer to the original values

Vue.config.devtools = false;

new Vue({
  el: '#app',
  data() {
    return {
      list: [],
      originalList: [],
      search: '',
    }
  },
  mounted() {
    for(let i = 1300; i <= 1400; i  ) {
      this.originalList.push(i.toString())
    }
    this.list = [ ...this.originalList ];
  },
  methods: {
    handleSearch() {
      this.list = this.originalList.filter(i => i.includes(this.search));
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <input @input="handleSearch()" v-model="search" placeholder="search number" />
  <ul>
    <li v-for="(item, i) in list" :key="i">{{item}}</li>
  </ul>
</div>

  • Related