0 day streak
javascript / beginner
Snippet

Removing Duplicate User Tags Using JavaScript Set in Vue

The JavaScript Set object stores unique values of any type. By combining the spread operator with a Set, you can quickly merge a new tag with an existing reactive array in Vue while automatically discarding duplicates.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
import { ref } from 'vue';
const tagList = ref(['javascript', 'vue', 'frontend']);
function addUniqueTag(newTag) {
const cleanTag = newTag.trim().toLowerCase();
if (cleanTag) {
const uniqueSet = new Set([...tagList.value, cleanTag]);
tagList.value = Array.from(uniqueSet);
}
}
vue
Breakdown
1
const tagList = ref(['javascript', 'vue', 'frontend']);
Initializes a reactive array storing the current list of tag strings.
2
const cleanTag = newTag.trim().toLowerCase();
Trims surrounding whitespace and converts the incoming tag to lowercase for uniform comparison.
3
if (cleanTag) {
Guards against empty strings before performing the set operation.
4
const uniqueSet = new Set([...tagList.value, cleanTag]);
Spreads existing tags and the new tag into a Set, which automatically drops duplicate entries.
5
tagList.value = Array.from(uniqueSet);
Converts the Set back into a standard array and assigns it to the reactive ref.