Remove duplicate values from Vue.js array using ES6

in Code Write a comment

Learn how to easily remove duplicates from an array.

Let’s make a very simple JavaScript array of products.

  data: {
    products: ['Oculus', 'Google Glass', 'Microsoft Hololens', 'Oculus', 'Varjo']
  }

Note that we’ve got duplicate records for ‘Oculus’. Now, let’s create a method that will create a new array of unique products.

ES6 example

new Vue({
  el: "#app",
  data: {
    products: ['Oculus', 'Google Glass', 'Microsoft Hololens', 'Oculus', 'Varjo']
  },
  methods: {
    removeDuplicates () {
      this.products = [ ...new Set(this.products) ]
    }
  }
})

removeDuplicates() method uses a Set object, which stores unique values of any type, and a Spread operator (three dots in JavaScript), which expands a new list as an array.

The result

Plain JavaScript example

var products = ['Oculus', 'Google Glass', 'Microsoft Hololens', 'Oculus', 'Varjo'];

var uniq = [ ...new Set(products) ];

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/vue-js-add-to-array

PS: Make sure you check other JavaScript tutorials, e.g. add item to the array if doesn’t exist in Vue.js/ES6 or how to get the last item in Vue.js array.

Write a Comment

Comment