Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums JavaScript Loop for longest array

  • This topic is empty.
Viewing 3 posts - 1 through 3 (of 3 total)
  • Author
    Posts
  • #43235

    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 :(

    #127432
    pixelgrid
    Participant

    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
    }

    }

    #127460

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

    Thank tho, you helped.

Viewing 3 posts - 1 through 3 (of 3 total)
  • The forum ‘JavaScript’ is closed to new topics and replies.