VueJs array data property: .includes() not finding integer value

Viewed 530

This is no doubt down to my limited knowledge on the subject, but I can't seem to figure out how to check whether the integer value is already stored on the data property of array type. I know the property is of the Observer type and it always seem to return false when asked:

this.selected.includes(value)

Here's my complete example - please note I'm actually casting value to Number to ensure that all numbers are emitted as such rather than string.

<script>
  export default {
    data () {
      return {
        selected: [],
      };
    },
    methods: {
      update (event) {
        const value = this.castOption(event.target.value);
        if (this.selected.includes(value)) {
          this.selected = this.selected.filter(element => element !== value);
        } else {
          this.selected.push(value);
        }
        this.$emit('input', this.selected);
      },
      castOption(value) {
        return isNaN(value) ? value : Number(value);
      },
    },
  }
</script>

So what I'm after is a simple way to determine whether the value is already in the selected array.

1 Answers

Sometimes when includes is not working, it is because you are searching for a different object that has the same value.

Try findIndex and then set a breakpoint to see why the equality test fails. Or log cases inside the loop.

You may find it is better to compare an id field inside your object instead of object instances.

if (this.selected.findIndex(it => it === value) > -1) {
}
if (this.selected.findIndex(it => { 
  console.log('comparing', it, value)
  return it === value
  }) > -1) {
}
Related