Is there an equivalent of ruby's any
method for arrays but in javascript? I'm looking for something like this:
arr = ['foo','bar','fizz', 'buzz']
arr.any? { |w| w.include? 'z' } #=> true
I can get a similar effect with javascript's forEach
method but it requires iterating through the entire array rather than short-circuiting when a matching value is found the way ruby's any
method does.
var arr = ['foo','bar','fizz', 'buzz'];
var match = false;
arr.forEach(function(w) {
if (w.includes('z') {
match = true;
}
});
match; //=> true
If I really wanted to short-circuit, I could use a for loop, but it's really ugly. Both solutions are super verbose.
var arr = ['foo','bar','fizz', 'buzz'];
var match = false;
for (var i = 0; i < arr.length; i++) {
if (arr[i].includes('z')) {
match = true;
i = arr.length;
}
}
match; //=> true
Any thoughts?
Is there an equivalent of ruby's any
method for arrays but in javascript? I'm looking for something like this:
arr = ['foo','bar','fizz', 'buzz']
arr.any? { |w| w.include? 'z' } #=> true
I can get a similar effect with javascript's forEach
method but it requires iterating through the entire array rather than short-circuiting when a matching value is found the way ruby's any
method does.
var arr = ['foo','bar','fizz', 'buzz'];
var match = false;
arr.forEach(function(w) {
if (w.includes('z') {
match = true;
}
});
match; //=> true
If I really wanted to short-circuit, I could use a for loop, but it's really ugly. Both solutions are super verbose.
var arr = ['foo','bar','fizz', 'buzz'];
var match = false;
for (var i = 0; i < arr.length; i++) {
if (arr[i].includes('z')) {
match = true;
i = arr.length;
}
}
match; //=> true
Any thoughts?
Share Improve this question asked Jun 23, 2015 at 1:40 williamcodeswilliamcodes 7,2869 gold badges37 silver badges59 bronze badges 2- developer.mozilla/en-US/docs/Web/JavaScript/Reference/… – Sean Hill Commented Jun 23, 2015 at 1:44
- Array.prototype.some. Just had to put in a reference to ECMA–262 ed6 now that it's the specification. :-) – RobG Commented Jun 23, 2015 at 1:54
2 Answers
Reset to default 9You are looking for the Array.prototype.some
method:
var match = arr.some(function(w) {
return w.indexOf('z') > -1;
});
In ES6:
const match = arr.some(w => w.indexOf('z') > -1);
arr.filter( function(w) { return w.contains('z') }).length > 0