I have two arrays. For example:
var bool = [true, false, true];
var vals = ['hi','med','lo'];
Using jQuery, I’d like to loop through them so that I can test each bool, and set a var equal to the highest available value from the vals array after the first true from the bool array:
var value = ( bool[0] ) ? vals[0] || vals[1] || vals[2] :
( bool[1] ) ? vals[1] || vals[2] : vals[2] ;
I’d like to make this work in a way that the arrays could have more values (but the size of the one would always match each.) Is it possible to pull this off with an .each function?
EDIT: It appears that you need the first truthy value from
valsandbool. Here’s a solution that doesn’t require any functions.I misunderstood the question to think that the arrays need to be truthy at the same indices. Now I see that the first true
boolindex is just the starting point forvals. Fixed.To explain, we have two
whileloops. In both of them, the typical{...}block statement has been replaced by an;empty statement. This is because all the work is done by the expressions between the(...).The first loop simply increments
iuntil a truthy value is found inbool. That setsito the starting point for the second loop.The second loop does the same thing as the first, except that each time the expression runs, it sets the current
val[i]to thevaluevariable. It does this as long asvalueis assigned a “falsey” value.This is effectively the same as your
val[0] || val[1] || val[2]part, except it will always begin wherever theboolloop lefti.So once
valuegets a “truthy” value, oriexceeds the last index in thevalsarray, the loop will quit. At this point,valuewill hold either the “truthy” value that was found, orundefinedif none was found.As a function:
DEMO: http://jsfiddle.net/W9uBb/