treehouse : what would you like to learn today?
Web Design Web Development iOS Development

Loop for longest array

  • i have 2 arrays i need to know which one is longer and loop for it.

    I have no clue how to do this and searching did not help :(

  • Every array in javascript has a length property. you could compare the two and loop the array with the bigger length.

    var length1 = array1.length,
     length 2 = array2.length;
    
    if( length1 > length2 ){
        for(var i = 0 ; i < length1; i++){
         // stuff if array 1 is bigger
       }
    }else if(length2 > length1){
      for(var j = 0; j< length2; j++){
      // stuff if array 2 is bigger
     }else{
      //if equal
    }
    

    }

  • That's actually pretty logic and easy, guess it was a brainfart.

    Thank tho, you helped.