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.

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.

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


Renat Galyamov

Hi, I'm Renat Galyamov

I'm a founder of Wonder.store and MED24.KZ.

A front-end developer with over 9 years of experience building businesses together with founders as well as large enterprises, such as Accenture, The British Museum, Admiral, Kimberley Process, 21st Century Fox and many others.

Subscribe to get my best articles in your inbox first


Join hundreds of weekly readers

I share my coding tips 💻, write about useful services ✌️ and share photos from beautiful places ⛰️

Check if an item already exists in an array in Vue.js/Vuex/ES6 #vuejs #vue #code #tutorial https://t.co/T3r4fkHPvE

12:48 PM Apr 9thView tweet



Write a Comment

Comment