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.

Hi, I'm Renat 👋


ES6 example

new Vue({
  el: "#app",
  data: {
    products: ['Oculus', 'Google Glass', 'Microsoft Hololens', 'Oculus', 'Varjo']
  methods: {
    removeDuplicates () {
      this.products = [ 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 = [ Set(products) ];

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 Vue.js 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.

Incoming search terms:

A collection of UI components for
Bootstrap 4/5 and Vue.js

Get now

Write a Comment