Reputation: 8171
I have a simple array:
var c = [4,5,6,7,8,9,10,11,12];
I am iterating through the array to try and return the value which meets the condition:
$.each(c, function() {
// I need to pass each value from the array as the
// last argument in the function below
var p = get_shutter_price( width, height, c );
if ( p > 0 ) {
// Return the value from the array which allowed the condition to be met
console.log( c );
}
});
This does not work as expected because the entire array is being passed into the function.
How do I return the value form the array which allowed the condition to be met?
For example, if the number 8 from the array is the one that returns a price greater than 0, then return 8.
Upvotes: 0
Views: 1719
Reputation: 54649
Provided you want all values from c
that meet the conditions, simply filter
var c = [4,5,6,7,8,9,10,11,12];
var conditionsMet = c.filter(function (value) {
return 0 < get_shutter_price(width, height, value);
});
with conditionsMet[0]
then being the first to meet the conditions.
Upvotes: 2
Reputation: 966
As I understand correctly you need array.prototype.filter
method to filter your array depend on condition.
var b = c.filter(function(val) {
return val > 0;
});
in your case just put your condition like this:
var b = c.filter(function(val) {
return get_shutter_price( width, height, val ) > 0;
});
It will return you a new array with this condition.
Upvotes: 1
Reputation: 2364
jQuery.each(c, function(index, item) {
// do something with `item`
});
In your code you missed to pass index and item as arguments to function (here index is optional)
Upvotes: 0
Reputation: 2031
use this
instead of c
, to pass the current iterating value, and you are 100% right that the whole array is passed when you use c
, so use this
to pass the current item which is being iterated -
$.each(c, function() {
// I need to pass each value from the array as the
// last argument in the function below
var p = get_shutter_price( width, height, this );
if ( p > 0 ) {
// Return the value from the array which allowed the condition to be met
console.log( this );
}
});
Upvotes: 0
Reputation: 2397
According to the docs there are two parameters you can use in the callback function, the first is the index of the item you are iterating over, the second is the value of the item.
$.each(c, function(index, val) {
// I need to pass each value from the array as the
// last argument in the function below
var p = get_shutter_price( width, height, val );
if ( p > 0 ) {
// Return the value from the array which allowed the condition to be met
console.log( c=val );
}
});
Upvotes: 0