DEV Community

loading...

Discussion on: "for" vs. "forEach" and the value of documentation

Collapse
quantumsheep profile image
Nathanael Demacon • Edited

I see all the solutions in the comments, you can also do this with the filter method:

const greeterThan = num => array1.filter(n => n >= num).length > 0;

OR (basically the same)

function greeterThan(num) {
  return array1.filter(n => n >= num).length > 0;
}
Collapse
qm3ster profile image
Mihail Malo

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()