How to check array contains a value in VueJS?

Hi Friends 👋,

Welcome To SortoutCode! ❤️

Today I am going to show you How do you check the array contains a value in VueJS.

Table of contains

  • Define names array for test
  • Using the Output of Array.includes()
  • Check Array contain value

Let’s start the today’s tutorial How do I check the array contains a value in VueJS?

Define names array for test

Let’s define the number in data of the FirstComponent.vue component for testing purposes.

FirstComponent.vue

<script>
export default {
    name: 'FirstComponent',
    data() {
        return{
            names : ["Welcome","to","Sortcode","Sortoutcode"],
        }
    },
}
</script>

Data is used to define properties in a particular component. In a single-file component, data() is a function that returns a set of properties that have been defined in the function.

we define the names array you can see that.

Using the Output of Array.includes()

The includes() method return the true if the value exists else return the false.

For Example:

<script>
export default {
    name: 'FirstComponent',
    data(){
        return{
            names : ["Welcome","to","Sortcode","Sortoutcode"],
        }
    },
    mounted(){
        console.log("Sortcode includes, ",this.names.includes('Sortcode'));
        console.log("game includes, ",this.names.includes('game'));
    },
}
</script>

Let’s check the output of includes() method examples.

Output

include() Method

Check Array contains the value

Let’s check the output of the full code.

FirstComponent.vue

<template>
    <div>
        <h1>Welcome to SortoutCode</h1>
    </div>
</template>
<script>
export default {
    name: 'FirstComponent',
    data(){
        return{
            names : ["Welcome","to","Sortcode","Sortoutcode"],
        }
    },
    mounted(){
        if(this.names.includes('Sortcode')){
            console.log("'Sortcode',", "Value Exist");
        }else{
            console.log("'Sortcode',", "Value Not Exist");
        }
    },
}
</script>

For now, let’s check the output.

Output

include() Method

All the best 👍.

Follow me on Twitter