When you want an array to only consist of unique elements, you'll need to control when you push to it.
More specifically, you'll need to first check if an element exists in the array before pushing it.
In this post, we'll learn how you can create and maintain an array of unique values and only push an element to it if it doesn't already exist.
Checking if an element exists in an array
To determine if an element can be pushed to our array, we'll need to first check if it exists in the array.
The best way to check if an element exists in an array of primitives is to use the includes() method.
This method takes an element and returns a boolean value.
JAVASCRIPTconst array = [1, 2, 3, 4, 5];
const value = 6;
const exists = array.includes(value);
console.log(exists);
BASHfalse
If your array uses objects, you can use findIndex and define a custom function to determine if the element was found.
The findIndex method will return to you the index of the element where your custom function returns true.
When the element is not found, the method will return an index of -1.
Since it just returns a number, you will need to compare it to -1 to get a boolean.
JAVASCRIPTconst array = [{ id: 1 }, { id: 2 }, { id: 3 }];
const value = { id: 4 };
const exists = array.findIndex(element => element.id === value.id) > -1;
console.log(exists);
BASHfalse
Pushing an element to an array
Now that you've determined how to check if an element exists in an array, you can use the push() method to push an element to the array.
Here's the example using primitives:
JAVASCRIPTconst array = [1, 2, 3, 4, 5];
const value = 6;
const exists = array.includes(value);
if (!exists) {
array.push(value);
}
console.log(array);
BASH(6) [1, 2, 3, 4, 5, 6]
Here's the example using objects:
JAVASCRIPTconst array = [{ id: 1 }, { id: 2 }, { id: 3 }];
const value = { id: 4 };
const exists = array.findIndex(element => element.id === value.id) > -1;
if (!exists) {
array.push(value);
}
console.log(array);
BASH(4) [{…}, {…}, {…}, {…}]
0: {id: 1}
1: {id: 2}
2: {id: 3}
3: {id: 4}
length: 4
Conclusion
In this post, we learned how to maintain a unique array of values and only push an element to it if it doesn't already exist.
Make sure to remember that for primitive values, you should use includes() to check if an element exists in an array, but for objects, you should use findIndex().
Hopefully, this was helpful to you. Thanks for reading!
Getting Started with TypeScript
How to Install Node on Windows, macOS and Linux
Create an RSS Reader in Node
How to Serve Static Files with Nginx and Docker
How to Set Up Cron Jobs in Linux
Best Visual Studio Code Extensions for 2022
Getting Started with Deno
How to deploy a MySQL Server using Docker
Learn how to use v-model with a custom Vue component
Getting Started with Handlebars.js
Build a Real-Time Chat App with Node, Express, and Socket.io
Building a Real-Time Note-Taking App with Vue and Firebase
