[Vuejs]-Vue Js using forEach loop to compare array objects, prints out value multiple times

3👍

You can use Array.find:

var isFound = this.todos.find(function (entry, index) {
    if (entry.text === this.checkTravelerId) {
        return true;
    }
})

if (isFound) { 
    console.log("already inserted");
} else {
    console.log("new id");
}

1👍

Rather than looping, I would use Javascript’s Array.find() method [documentation here]:

new Vue({
  el: "#app",
  data: {
    checkTravelerId: '',
    todos: [
      { text: "123", id:'1'},
      { text: "456", id:'2'},
      { text: "789", id:'3'},
      { text: "012", id:'4'}
    ]
  },
  methods: {
    dontknow(){
      var found = this.todos.find((todo) => {
        return todo.text == this.checkTravelerId
      })

      // If nothing is found, Array.find() returns undefined, which is false-y

      if (found) {
        console.log("already inserted")
      } else {
        console.log("new id")
      }
    }
  }
})

1👍

You can try this:

new Vue({
  el: "#app",
  data: {
    checkTravelerId: '',
    todos: [
      { text: "123", id:'1'},
      { text: "456", id:'2'},
      { text: "789", id:'3'},
      { text: "012", id:'4'}
    ],
  },
  methods: {
    dontknow() {
      var result = this.todos.findIndex(player => this.checkTravelerId === player.text);
      if(result > -1) {
        console.log("already inserted");
      } else{
        console.log("new id");
      }
    },
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <h2>Player Input Field</h2>
   <input type="text" name="" v-model="checkTravelerId"/>
   <!-- if 123 inserted its suppose to say already inserted for only one time-->
   <!-- if inserted 908 its suppose to say new id for only one time -->
   <button variant="primary" v-on:click="dontknow();">SUBMIT</button>
</div>
👤Syed

0👍

you can try to using map, and array.indexOf

new Vue({
  el: "#app",
  data: {
    checkTravelerId: '',
    todos: [
      { text: "123", id:'1'},
      { text: "456", id:'2'},
      { text: "789", id:'3'},
      { text: "012", id:'4'}
    ]
  },
  methods: {
    dontknow(){

         if (this.todos.map(function(e) {return e.text}).indexOf(this.checkTravelerId) > -1) {
 console.log("already inserted");
}else {
         console.log('new id')

}

      },
  }
})

0👍

Following Lanny Bose’s great answer, I would suggest using Array.some() method instead to work directly with Boolean values, just replace “find” with “some”.

👤Soil92

Leave a comment