Search code examples
javascriptarraysboolean-operations

loop though an array and return a set of array index's values concatenated in one variable


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


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.