Vue.js’s indexof method : The indexOf()
method is a built-in function in JavaScript that allows you to search for an item in an array or an object and returns the index of the first occurrence of the item
If the searchElement
is found in the array or object, the method returns the index of its first occurrence. If the searchElement
is not found, the method returns -1.
It’s important to note that the indexOf()
method is case-sensitive. This means that if you search for the lowercase string “hello” in an array that contains the uppercase string “Hello”, the method will return -1.
If the searchElement
appears more than once in the array, the indexOf()
method will return the index of the first occurrence.
In Vue.js, you can use the indexOf()
method to find the index of the first given element that appears in an array. The method works the same way in Vue.js as it does in JavaScript.
You can try out the indexOf()
method using the “run online” feature, which allows you to see the results of your code in real-time.
Get the index of an array item in Vue js Method:
In Vue, you can use the indexOf
method to find the index of an element in an array. For example, if you have an array of countries and you want to find the index of “India”, you can use this.country.indexOf('India')
. The resulting index will be stored in the result
data property.
The JavaScript indexof method can be used to find the first index given item in Vue.js.
Vue.js Array IndexOf Function Example
<div id="app">
<button @click='myFunction' class='btn btn-primary'>Find Index of India </button>
<p>Index is: {{result}}</p>
</div>
<script type="module">
import { createApp } from 'vue'
createApp({
data()
{
return{
country:['Australia','England','America','India','China','Russia'],
result : ''
}
},
methods:{
myFunction(){
this.result = this.country.indexOf('India');
},
}
}).mount('#app')
</script>
The Output of above example is given as below:
Get index of item in array from object value
Use Vue’s indexOf()
method to find values in an array of objects. In data()
, define an array of objects with properties such as countryName
and capitalName
. In methods
, use the map()
method to extract the countryName
values and then apply the indexOf()
method to find the index of the target value, such as 'India'
.
Vue.js Array IndexOf Function from Object Example
<div id="app">
<button @click='myFunction' class='btn btn-primary'>Find Index of India </button>
<p>{{result}}</p>
</div>
<script type="module">
import { createApp } from 'vue'
createApp({
data()
{
return{
countries:[
{
'countryName':'Australia',
'capitalName':'Canberra'
},
{
'countryName':'England',
'capitalName':'London'
},
{
'countryName':'India',
'capitalName':'New Delhi'
},
],
result : ''
}
},
methods:{
myFunction(){
this.result = this.countries.map((country) => country.countryName).indexOf('India')
},
}
}).mount('#app')
</script>