Array.prototype.filter() is probably the least suitable here, for two reasons:
1) It allocates an output array.
2) Even if the very first element matches, it will still test all of the remaining elements.
In contrast, Array.prototype.some() only returns a boolean, and never executes the predicate past the first match. In other words, it implements the optimizations one would do in the for loop when does at least something match? is the question.
If you do care about the value, there's Array.prototype.find(), and if you actually need the key/index yourself, for example to replace the value in place or look up a matching index in another array, there's Array.prototype.findIndex()
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
I see all the solutions in the comments, you can also do this with the filter method:
OR (basically the same)
Array.prototype.filter()
is probably the least suitable here, for two reasons:1) It allocates an output array.
2) Even if the very first element matches, it will still test all of the remaining elements.
In contrast,
Array.prototype.some()
only returns a boolean, and never executes the predicate past the first match. In other words, it implements the optimizations one would do in thefor
loop when does at least something match? is the question.If you do care about the value, there's
Array.prototype.find()
, and if you actually need the key/index yourself, for example to replace the value in place or look up a matching index in another array, there'sArray.prototype.findIndex()