Check if an item already exists in an array in Vue.js/Vuex/ES6

in Code Write a comment

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.


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'];

// expected output: true


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.

If you find this post useful, please let me know in the comments below. 
Renat Galyamov

Want to share this with your friends?

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

Write a Comment