Array.push() if does not exist?
Prevent duplicates by using includes
prior to push
for uniqueness:
For object arrays, find
or findIndex
can be used to compare object properties prior to pushing:
Quick Fix: Strings and Numbers Arrays
Exclude Dupes with Ease
Directly utilize includes
or indexOf
to check for the presence of an item (standard for strings or numbers) before pushing.
The Novelty of Uniqueness
Switch to using a Set to keep your array unique. You can recklessly add items without worry for duplicates.
Dealing with Object Arrays
Sherlock Holmes-ing Properties
To ensure there are no duplicate objects, property comparison comes to the rescue in arrays of objects.
Reusable Code? Yes Please!
Encapsulate the logic into a 'pushIfNotExist' function for easy reusability.
Make ES6 Thy Knight
Enhance readability by summoning the power of ES6 features like filter
and concat
.
Nerd Corner: Performance Obsession
When performance is a calling card, the size and complexity of your array should be considered. The indexOf
, find
, and includes
have diverse speed records that might affect performance, especially with larger arrays.
Code Cleanliness and Tricks
Avoid extending native objects like Array.prototype
in shared environments. This can lead to surprise parties no one wants to attend!
Writing clear and maintainable code is your golden ticket to longevity in projects. Utility functions such as pushIfNotExist
help create cleaner code, making it easy to test and read.
Was this article helpful?