I need to perform an action in JavaScript code only if no array elements fulfill a condition. What’s the optimal way to do it?
In this particular case, I need to push something to the dataLayer only if it’s not already present. Here’s what I did:
if (!window.dataLayer.some(
(element) => element.event === 'some_label',
)) {
gtm.push(someTrackingObject);
}
Is there a better / more concise way?
3
Answers
You can use
.every()
If you want to check if no elements fulfull one specific condition, just inverse the condition
Using
.some()
is good enough, so.every()
is just an alternative way.Your current approach using Array.prototype.some() is optimal for checking if no array elements fulfill a condition, as it stops iterating over the array as soon as the condition is met, avoiding unnecessary iterations.
However, if you want a more concise version, you can use the Array.prototype.indexOf() method to achieve the same result:
Here, Array.prototype.indexOf() returns the first index at which a given element can be found in the array, or -1 if it is not present. Note that this approach assumes that someTrackingObject is unique in the window.dataLayer array.
Both approaches have their pros and cons:
In summary, your current approach using Array.prototype.some() is optimal for checking if no array elements fulfill a condition, and you can consider using Array.prototype.indexOf() for a more concise version if someTrackingObject is unique in the window.dataLayer array.
What you did already is a good way to do it. You can also use
.every()
and check for!== 'some_label'
.If you have a lot of data you can use a map or set to be more efficient when it comes to lookup time. But this only makes sense when you have multiple lookups and a large array size.
Update
Search for the element.
.find
exits on the first match so you don’t have to check every element in the array.