Question

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 ).

Was it helpful?

Solution

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.

OTHER TIPS

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;
};

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;
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top