Vue Js Array Find Index by Value

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.

written

reviewed

updated

Thanks for your feedback!
Your contributions will help us to improve service.
The JavaScript indexof method can be used to find the first index given item in Vue.js.
Example 1 : Array Indexof Method using Vue js
Copied to Clipboard
xxxxxxxxxx
<script type="module">
import { createApp } from 'vue';
createApp({
data() {
return {
countries: ['Australia', 'England', 'America', 'India', 'China', 'Russia'],
result: ''
};
},
methods: {
findIndex() {
this.result = this.countries.indexOf('India');
}
}
}).mount('#app');
</script>
The Output of above example is given as below:
Get index of item in array of object value in Vue Js
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'
.
Example 2 : Using Vue.js to Find Country Index: Example with 'Australia
Copied to Clipboard
xxxxxxxxxx
<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('Australia')
},
}
}).mount('#app')
</script>
The Output of above example is given below:
Ad