Using includes
(or filter
, some
) can be expensive. If you have a large array (hundreds or more), or you need to determine inclusion often, then it can be very slow. That's because these functions loop through the array looking inside of the objects with the function you provide until the outcome is reached.
If performance is a concern you may find that building an indexing object is best for you. For example:
const byIndices = {};
arr.forEach(obj => byIndices[obj.index] = obj);
if (byIndices[12]) console.log("item 12 is",byIndices[12].data)
With this approach you loop through the entire array once (the forEach
loop) to build the indexing object byIndices
, then you can use direct object syntax to not only determine existence, but also get at the object.
Since Javascript is optimized for working with objects, doing lookups like byIndices[val]
are very quick, and since it's all object references it's not too bad for memory use either.
However for small arrays, or if you only need to find entries occasionally then it's probably simplest to use some
or filter
to do the job.