0

The question it's not so relevant but what I want to achieve is the next :

var some_array = [Modernizr.json, Modernizr.csstransforms];

var tests = function() {
    for (var i = some_array .length - 1; i >= 0; i--) {
       ...
    };

    return  Modernizr.json && Modernizr.csstransforms;
};

I keep thinking of the logic that would do what I tried to show you, but I cannot figure it out. Basically I need to loop the array of tests and return a boolean operation between the tests, to be more specific I want to take the array [Modernizr.json, Modernizr.csstransforms] and I want to return Modernizr.json && Modernizr.csstransforms and so on ( if there are more values in the array ).

4
  • you mean var tests ? no, it isn't, should it be ? Commented Oct 21, 2012 at 12:58
  • I don't know tbh. In it's current state I have no idea what it is you are looking for. Could you please clarify your question? Commented Oct 21, 2012 at 13:02
  • are you trying to do some_array.join() ? Commented Oct 21, 2012 at 13:12
  • I don't think so ... is it so hard to understand ? I want to get from an array to an boolean operation ( && ) between the array values ... isn't this clear enough ? because I have no idea how to explain this in any other way (: Commented Oct 21, 2012 at 13:23

3 Answers 3

1

Use reduce:

return some_array.reduce(function(a, b){ return a && b; });

or reduceRight if you want to iterate backwards.

If you want to break the loop once a falsy value is encountered, you also could use every.

Sign up to request clarification or add additional context in comments.

3 Comments

reduce is not supported in IE8 and lower
and what if I have more than two values, what if there are 15 ? will the above statement still work ?
@Roland: some_array can be an array of any length (should be at least 2 for reducing)
1

If you want to check if all values in your array are true, you can do this:

var some_array = [Modernizr.json, Modernizr.csstransforms];

var tests = function() {
    var result = true;
    for (var i = some_array .length - 1; i >= 0; i--) {
        result = result && some_array[i];
    };
    return result;
};

Comments

0

I found a good solution for what I was looking for, based on @Bergi's answer :

some_array.reduce(function(previousValue, currentValue, index, array){
    return previousValue && currentValue;
});

1 Comment

Yes, that's exactly my solution…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.