Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the equivalent of prototype .any in Jquery?

We have one function called .any in Prototype. I want the same like in Jquery.

My Prototype code is:

 if (item_name == '' || $R(1,ind).any(function(i){return($F("bill_details_"+i+"_narration") == item_name)})) {
     alert("This item already added.");
 }

I want to perform the Equivalent function using Jquery.

Please help me to achieve the desired output. Thanks in Advance..

like image 597
Can Can Avatar asked Mar 27 '13 10:03

Can Can


2 Answers

For IE 9+ it's built in:

The some() method tests whether some element in the array passes the test implemented by the provided function.

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/some

[2, 4, 6, 8, 10].some(function(n) { return n > 5; });
// -> true (the iterator will return true on 6)

For IE 8 and below:

Prototype any

[2, 4, 6, 8, 10].any(function(n) { return n > 5; });
// -> true (the iterator will return true on 6)

You can use jQuery.grep:

jQuery.grep([2, 4, 6, 8, 10], function(n) { return n > 5; }).length > 0;
// -> true (as grep returns [6, 8, 10])

Underscore _.any or _.some

_.any([2, 4, 6, 8, 10], function(n) { return n > 5; });
// -> true (the iterator will return true on 6)
like image 83
jantimon Avatar answered Oct 27 '22 21:10

jantimon


ES5 has a built-in function called Array.prototype.some which tests for whether any element in an array matches a predicate function, and which stops iterating as soon as a matching element is found.

.some(function(el) {
    return el.value === item_name;
});

Your problem then just becomes one of creating an array of the desired elements, which is harder than it would be in Prototype because there's no "range" operator in jQuery. Fortunately $.map iterates over empty elements, even though the built-in Array.prototype.map doesn't so you can use new Array(ind):

var found = $.map(new Array(ind), function(_, x) {
    return "bill_details_" + (x + 1) + "_narration";
}).some(function(id) {
    var el = document.getElementById(id);
    return el && (el.value === item_name);
});

The link above includes a shim for .some for older browsers.

like image 37
Alnitak Avatar answered Oct 27 '22 22:10

Alnitak