Preventing Duplicate Array Values in Vue 3

William Schulte
Vue.js Developers
Published in
7 min readDec 18, 2022

In an earlier post, I wrote about my obsession with JavaScript array shuffling in the context of Vue.js. I’ve lately found myself fascinated with methods for preventing the injection of duplicate values into arrays. The focus of this article will therefore be on how to use various JavaScript methods to prevent duplicate array values in Vue-based projects.

For this project, we’ll build a simple Vue 3/TailwindCSS interface that prompts the user to input number values, which in turn are pushed to an array. The values of the array are then assigned to 5 slots on the screen. If the user attempts to input the same value twice, they’ll be met with an alert that says No Duplicates Allowed! before proceeding with additional inputs. Over the course of this article, we’ll look at 3 different array method configurations developers can use to prevent duplicate array values (when necessary) in Vue 3.

Let’s get started!

Project Setup

For this project, we’ll be using a simple CDN-based Vue 3 configuration with TailwindCSS, instead of the Tailwind + Vite setup covered in my other posts.

First, open up your IDE and copy and paste the following template code to an HTML file:

<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<script src="https://cdn.tailwindcss.com"></script>

<div id="demo" class="max-w-7xl mx-auto py-6 sm:px-6 lg:px-8 bg-gray-100">
<div class="px-4 py-6 sm:px-0">
<input v-model="number" type="number" class="border-solid border-2 px-5 py-1.5 mr-2 mb-2 rounded" />
<button @click="submit" type="submit" class="text-white bg-blue-700 hover:bg-blue-800 font-medium rounded-lg text-sm px-5 py-2.5 mr-2 mb-2">
Submit
</button>

<div class="flex items-center justify-center py-16 mt-12">
<div v-for="num in finalArray" :key="num.id" class="w-72 h-72 m-2">
<div class="flex justify-center items-center w-full h-full p-8 text-9xl rounded-md shadow-lg border-solid border-2 border-sky-500">
{{ num.val }}
</div>
</div>
</div>
</div>
</div>

Next, set up the following script block below the template:

<script>
const { ref } = Vue
const app = Vue.createApp({
setup() {
// functionality goes here

return {
// properties
};
}
})
app.mount('#demo')
</script>

Inside the setup() function and return block, add the binding properties and the submit() function that will be used to facilitate the inputting and pushing of values to the array:

<script>
const { ref } = Vue
const app = Vue.createApp({
setup() {

const numberValue = ref(null)
const numberArray = ref([])
const finalArray = ref([
{val: ''},
{val: ''},
{val: ''},
{val: ''},
{val: ''},
])

const submit = () => {

// add functionality to prevent duplicates here

finalArray.value = [
{val: numberArray.value[0]},
{val: numberArray.value[1]},
{val: numberArray.value[2]},
{val: numberArray.value[3]},
{val: numberArray.value[4]},
]

numberValue.value = ""
}

return {
numberValue, numberArray, finalArray, submit
};
},
})
app.mount('#demo')
</script>

So far we have a numberValue property that is bound to the input field. Each inputted value will be passed to an array called numberArray. We’ll then set each value of numberArray on the individual objects that make up finalArray, thus allowing each numberArray value to occupy an individual slot in the UI (see the above screenshot).

Now that we have our basic setup, let’s look at 3 examples of how to prevent duplicate array values!

1. find() method

The first example we’ll look at uses a find() method inside the submit() function to find existing values in numberArray.

const submit = () => {

//Example 1
const existingValue = numberArray.value.find(item => item === numberValue.value)
if (existingValue) {
alert('No Duplicates Allowed!');
return
}
numberArray.value.push(numberValue.value);

numberArray.value = [...numberArray.value.slice(0,5)]

finalArray.value = [
{val: numberArray.value[0]},
{val: numberArray.value[1]},
{val: numberArray.value[2]},
{val: numberArray.value[3]},
{val: numberArray.value[4]},
]

numberValue.value = ""
}

The find() method returns the first element in numberArray that satisfies the condition of item === numberValue.value. If the user attempts to input an existing value in the array, an alert message will be triggered. The return inside the existingValue conditional will then prevent the function from pushing the duplicate value into numberArray.

Since we’re dealing with only 5 value slots in the UI, we can prevent more than 5 values from being pushed to numberArray by adding a slice() method at the end of the array. We’ll then use a spread operator (…) to set the values of numberArray in a new copy of that array. We’ll employ a similar setup for preventing more than 5 values in the array in the next two examples.

The final script block with example 1 looks like the following:

<script>
const { ref } = Vue
const app = Vue.createApp({
setup() {

const numberValue = ref(null)
const numberArray = ref([])
const finalArray = ref([
{val: ''},
{val: ''},
{val: ''},
{val: ''},
{val: ''},
])

const submit = () => {

//Example 1
const existingValue = numberArray.value.find(item => item === numberValue.value)
if (existingValue) {
alert('No Duplicates Allowed!');
return
}
numberArray.value.push(numberValue.value);

numberArray.value = [...numberArray.value.slice(0,5)]

finalArray.value = [
{val: numberArray.value[0]},
{val: numberArray.value[1]},
{val: numberArray.value[2]},
{val: numberArray.value[3]},
{val: numberArray.value[4]},
]

numberValue.value = ""
}

return {
numberValue, numberArray, finalArray, submit
};
},
})
app.mount('#demo')
</script>

2. filter() method

In this example, we’ll use a filter() method to create a new array with unique values.

const submit = () => {

//Example 2
numberArray.value.push(numberValue.value)
const uniqueArray = numberArray.value.filter((value, index, array) => array.indexOf(value) === index);

if (numberArray.value.indexOf(numberValue.value) !== numberArray.value.lastIndexOf(numberValue.value)) {
alert('No Duplicates Allowed!');
}

numberArray.value = [...uniqueArray.slice(0,5)]

finalArray.value = [
{val: numberArray.value[0]},
{val: numberArray.value[1]},
{val: numberArray.value[2]},
{val: numberArray.value[3]},
{val: numberArray.value[4]},
]

numberValue.value = ""
}

Inside the filter() method, we’ll use the indexOf() method to target the first index of a given value in numberArray. If the user pushes only one instance of a value into numberArray, then array.indexOf(value) === index inside the filter() method will be equal, while the value is added to uniqueArray.

Meanwhile, if the user attempts to push another instance of an existing value into the array, then array.indexOf(value) will return the index of the first instance of the value in the array, while index will return the index of the second instance. In that case, array.indexOf(value) === index will NOT be equal, and the second instance of the existing value will NOT be added to uniqueArray. We’ll then use a spread operator (…) to set the values of uniqueArray in a new copy of the array, while in turn assigning that copy to numberArray.

Finally, we’ll use a conditional to handle the alert() for when a duplicate is detected. Inside the conditional, we’ll use indexOf() to target the index of the first instance of a given value, while lastIndexOf() will, as you probably guessed, target the index of the last instance of that same value. If they are not equal, that means the value targeted by lastIndexOf() is a duplicate value. The alert() will then be triggered.

The final script block with example 2 looks like the following:

<script>
const { ref } = Vue
const app = Vue.createApp({
setup() {

const numberValue = ref(null)
const numberArray = ref([])
const finalArray = ref([
{val: ''},
{val: ''},
{val: ''},
{val: ''},
{val: ''},
])

const submit = () => {

//Example 2
numberArray.value.push(numberValue.value)

const uniqueArray = numberArray.value.filter((val, idx, arr) => arr.indexOf(val) === idx);

if (numberArray.value.indexOf(numberValue.value) !== numberArray.value.lastIndexOf(numberValue.value)) {
alert('No Duplicates Allowed!');
}

numberArray.value = [...uniqueArray.slice(0,5)]

finalArray.value = [
{val: numberArray.value[0]},
{val: numberArray.value[1]},
{val: numberArray.value[2]},
{val: numberArray.value[3]},
{val: numberArray.value[4]},
]

numberValue.value = ""
}

return {
numberValue, numberArray, finalArray, submit
};
},
})
app.mount('#demo')
</script>

3. Set Object

In the final example we’ll use a Set object to create a collection of unique values, based on the values pushed into numberArray.

const submit = () => {

//Example 3
numberArray.value.push(numberValue.value)
if (numberArray.value.indexOf(numberValue.value) !== numberArray.value.lastIndexOf(numberValue.value)) {
alert('No Duplicates Allowed!');
}
numberArray.value = [...new Set(numberArray.value.slice(0,5))]

finalArray.value = [
{val: numberArray.value[0]},
{val: numberArray.value[1]},
{val: numberArray.value[2]},
{val: numberArray.value[3]},
{val: numberArray.value[4]},
]

numberValue.value = ""
}

If you’re new to this concept, a JavaScript Set is a collection of unique values, in which each value can only occur once. Passing numberArray into new Set will allow us to return a new copy of numberArray with unique values (no duplicates). We’ll also use the indexOf()/lastIndexOf() conditional like we did in example 2 to handle the No Duplicates Allowed! alert.

The final script block with example 3 looks like the following:

<script>
const { ref } = Vue
const app = Vue.createApp({
setup() {

const numberValue = ref(null)
const numberArray = ref([])
const finalArray = ref([
{val: ''},
{val: ''},
{val: ''},
{val: ''},
{val: ''},
])

const submit = () => {

//Example 3
numberArray.value.push(numberValue.value)
if (numberArray.value.indexOf(numberValue.value) !== numberArray.value.lastIndexOf(numberValue.value)) {
alert('No Duplicates Allowed!');
}
numberArray.value = [...new Set(numberArray.value.slice(0,5))]

finalArray.value = [
{val: numberArray.value[0]},
{val: numberArray.value[1]},
{val: numberArray.value[2]},
{val: numberArray.value[3]},
{val: numberArray.value[4]},
]

numberValue.value = ""
}

return {
numberValue, numberArray, finalArray, submit
};
},
})
app.mount('#demo')
</script>

We made it to the end! Now you know a few ways to prevent duplicate array values in Vue 3!

I really hope this helps. If you like this content, please take a moment to clap, comment, and subscribe!

Other posts from this author:

--

--

William Schulte
Vue.js Developers

Mobile App Developer, Coding Educator, LDS, Retro-gamer 🎮