This is a common task for front-end developers. There can be many ways to check if an element already exists in an array. In this tutorial, I’ll show you the way I do it.
Array.includes()
Suppose you have a list AR/VR headsets and you want to check if ‘Hololens’ already exists in your list/database. Here is how you can do it with ES2016 array.includes()
method:
var headsets = ['Hololens', 'Google Glass', 'Varjo'];
console.log(headsets.includes('Hololens'));
// expected output: true
Vuex
This is a Vuex example. We have a list of products in a Vuex state. Each product has a category id. Our goal is to get all the products in a certain category.
getProductsByCategoryID: (state) => (categoryID) => {
return state.products.filter((product) => {
return product.category.includes(categoryID)
})
}
In this example, we’re using getProductsByCategoryID
getter to filter through a list of products and selecting only those products that have a passed categoryID
.
We use two methods array.filter()
and array.includes()
. Filter()
method returns an array, whereas includes()
methods returns true
or false
as appropriate.
You can then get filtered products like so:
this.productsFiltered = this.$store.getters.getProductsByCategoryID(this.categoryID)
If you find this post useful, please let me know in the comments below.
Cheers,
Renat Galyamov
Want to share this with your friends?
👉renatello.com/check-if-item-exists-in-array-in-vuejs-vuex-es6
PS: Make sure you check other posts e.g. how to check if a user has scrolled to the bottom in Vue.js, how to do Vue.js polling using setInterval(), JavaScript/Vue.js print object in the console and how to get selected value on @change using Vue.js
Incoming search terms:
thx so much for this elegant solution
You’re very welcome!
Hey i need your little help for my project work in vuex can u please help me