Saif Md Towfiq Islam Saif Md Towfiq Islam - 4 months ago 77
Javascript Question

How to avoid duplicate values in the output of v-for loop in vuejs

I want to remove or filter out the duplicate values in the output of my v-for loop. So, that 'John' appears only once instead of appearing twice in the output. Is that possible to do in vuejs ?

JS

var app = new Vue({
el: "#app",
data: function () {
return {
searchFields: ['number', 'name'],
search: '',
items: [
{ name: 'Mary'},
{ name: 'John'},
{ name: 'John'},
{ name: 'William'}
]
};
}
});


Codepen

Answer

So by checking the filters-documentation you can see that you can write your own custom filters.

So by having myFilter you can define what you want to have in a method.

v-for="item in items | filterBy myFilter">

Now adding the method it should something like this:

let arr = [];

var app = new Vue({
  el: "#app",
  data: function () {
    return {
      searchFields: ['number', 'name'],
      search: '',
      items: [
        { name: 'Mary'},
        { name: 'John'},
        { name: 'John'},
        { name: 'William'}
      ]
    };
  },
  // this is where your filter method is defined
  methods: {
    myFilter: function(val) {
      if(arr.indexOf(val.name) === -1) {
        arr.push(val.name);
        return val.name;
      }
    }
  }
});

What this does is check if your value is in your array arr. If not, it adds it to the array, preventing duplicate items appearing later on.

So only if your item.name hasn't been displayed already, your filter returns the name to the view.

Check it out

*Maybe there is a nicer/easier solution to this, but good enough for now :)

Comments