Q:

multiple if stamens inside for loop

I have a for loop like so:
for(var i = 0; i < data.reviews.length; i++){
    if(data.reviews[i].rating.overall > 80){
      console.log(i);
      if(i > 1){
        console.log('more than 80 and more than 1');
      }
      else{
        console.log('more than 80 and only 1');
      }

    }
}

and a reviews array as follow:
"reviews":[
{
"rating":{"overall": 91}
},
{
"rating":{"overall": 77}
},
{
"rating":{"overall": 94}
},
{
"rating":{"overall": 74}
}
],

I have some conditions that I need to meet to append some HTML:
1) if the reviews overall is more than 80 and there is more than one reviews (append slide show)
2) if the reviews overall is more than 80 and there is only one review (append plain text, jus tone review without slideshow)
Based on the reviews data provided I should get console.log('more than 80 and more than 1'); printed only twice instead in my console I get:
more than 80 and only 1  
more than 80 and only 1  
more than 80 and more than 1

A:

If I'm understanding your problem correctly, then you simply need to change the inner if statement to check how many reviews there are - not the counter for iterating them...

var data = {
    "reviews": [
        {
            "rating":{"overall": 91}
        },
        {
            "rating":{"overall": 77}
        },
        {
            "rating":{"overall": 94}
        },
        {
            "rating":{"overall": 74}
        }
    ]
};

for (var i = 0, l = data.reviews.length; i < l; i++) {
    if (data.reviews[i].rating.overall > 80) {
        if (l > 1) {  // check the overall count, instead of the current index
            document.write('more than 80 and more than 1<br />');
        }
        else {
            document.write('more than 80 and only 1<br />');
        }
    }
}

