Scooter Daraf
Scooter Daraf

Reputation: 535

Two conditions in for loop

I have this code which im echoing data from jquery success .

   for(i = 0;i < dat.id.length; i++){

           // im echoing data here 
    }

and i want check for the highest value in dat.voteup

like that (It works)

    var maxvoteup = 0; 
    if (dat.voteup[i] - dat.votedown[i] ==maxvoteup) {
                    console.log(maxvoteup);
        //i want fetch maxvoteup here

     }

But i want make just one For loop not two . How can i do that pls?

EDIT:

  var maxvoteup = 0; 
    for (i = 0;i < (dat.voteup-dat.votedown).length ;i++) {
         if (dat.voteup[i] - dat.votedown[i]>maxvoteup) {
            maxvoteup = dat.voteup[i] - dat.votedown[i];
                    console.log(maxvoteup);
        //i want fetch maxvoteup here
      }
     }

EDIT2: this is what im getting in my jquery response , But actually my max vote is 10 not 8 . 8 is just voted up to 8 , but there is other votes which is 10.

   {"status":"success","message":[],"date_edited":[2016-04-21 21:31:25],"voteup":[],"votedown":[8],"id":[]}

Upvotes: 0

Views: 208

Answers (1)

smaili
smaili

Reputation: 1235

Your code is a little hard to read, but if I understand correctly I believe all you need to do is combine both into a single loop with maxvoteup defined outside.

var maxvoteup = 0;
for(i = 0;i < dat.id.length; i++){
    // echo data...

    // max upvote
    if (dat.voteup[i] - dat.votedown[i] == maxvoteup) {
      console.log(maxvoteup);
    }
}

EDIT:

Unfortunately getting the maximum value from a list requires you to iterate through the list, i.e., a maximum value cannot be found in constant time. I suggest you first find the maximum, and then proceed with your for loop.

Also, if you know your maximum is a list of numbers, you can actually use Javascript's apply to make the code a little cleaner:

var maxvoteup = Math.max.apply(Math, listOfMaxVotes);

See here: How does the Math.max.apply() work?

EDIT2:

If you want to continuously keep track of the maximum, then all you need to do is move the maxvoteup variable to outside of your response handlers so you can always keep track.

// global scope...
var maxvoteup = 0;

// your jquery response handler
var onSuccessData = function(data) {
  // get the highest possible max from the `voteup` and `votedown` lists
  var responseMax = Math.max.apply(Math, data.voteup.concat(data.votedown));

  // check if it's greater than our global maxvoteup
  if (responseMax > maxvoteup) {
    // if it is, then update our global `maxvoteup` to the new value
    maxvoteup = responseMax;
  }

  // continue with your other processing...
};

Upvotes: 1

Related Questions