Is there a Ruby equivalent of any method in javascript?

Is there an equivalent method ruby any

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 using javascript method forEach

, but it requires iterating through the entire array, and not short-circuit, when found appropriate value, as it makes the ruby method any

.

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 that was 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?

+3


source to share


2 answers


You are looking for a method Array.prototype.some

:



var match = arr.some(function(w) {
   return w.indexOf('z') > -1;
});

      

+7


source


arr.filter( function(w) { return w.contains('z') }).length > 0

      



0


source







All Articles