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
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
Share Improve this question asked Jul 25, 2016 at 17:42 Saif IslamSaif Islam 3011 gold badge7 silver badges19 bronze badges3 Answers
Reset to default 3So 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 :)
Vuejs filterBy provides 3 arguments to the filter function: value of the current item, the index of the item and the whole array. Following works without a temporary array:
methods: {
myFilter: function (val, idx, arr) {
for(var i = 0; i < idx; i++) {
if(arr[i].name === val.name) {
return false;
}
}
return true;
}
}
I used a puted value, as suggested by the Vuejs guide: https://v2.vuejs/v2/guide/list.html#Displaying-Filtered-Sorted-Results
puted: {
uniqueNames: function() {
var filtered_array = [];
for(var i =0; i < this.items.length; i++) {
if(filtered_array.indexOf(this.items[i].name) === -1) {
filtered_array.push(this.items[i].name)
}
}
return filtered_array;
}
}
With this v-for:
v-for="name in uniqueNames"
See my codepen