what is Array.any? for javascript
The JavaScript native .some()
method does exactly what you're looking for:
function isBiggerThan10(element, index, array) {
return element > 10;
}
[2, 5, 8, 1, 4].some(isBiggerThan10); // false
[12, 5, 8, 1, 4].some(isBiggerThan10); // true
JavaScript has the Array.prototype.some()
method:
[1, 2, 3].some((num) => num % 2 === 0);
returns true
because there's (at least) one even number in the array.
In general, the Array
class in JavaScript's standard library is quite poor compared to Ruby's Enumerable. There's no isEmpty
method and .some()
requires that you pass in a function or you'll get an undefined is not a function
error. You can define your own .isEmpty()
as well as a .any()
that is closer to Ruby's like this:
Array.prototype.isEmpty = function() {
return this.length === 0;
}
Array.prototype.any = function(func) {
return this.some(func || function(x) { return x });
}
Libraries like underscore.js and lodash provide helper methods like these, if you're used to Ruby's collection methods, it might make sense to include them in your project.
I'm a little late to the party, but...
[].some(x => !!x)