Search code examples
javascriptarraysfor-loopnested-loops

Javascript nested for array represent issue


I have two array that intersect two element as you see below. Normally this function should write as A, B, Y but it represents all value lista.length * listb.length

<script>
    window.onload = function(){     
        var lista = [];
        lista[0] = "A";
        lista[1] = "B";
        lista[2] = "Y";

        var listb = [];
        listb[0] = "A";
        listb[1] = "B";

        for(var i=0; i<lista.length; i++){
            for(var j=0; j<listb.length; j++){
                if(listb[j] == lista[i]){
                    document.write(listb[j] + "<br/>");
                }else{
                    document.write(lista[i] + "<br/>");                 
                }               
            }
        }
    }
</script>

Solution

  • You could print only the element of the outer loop

    window.onload = function() {
        var lista = ["A", "B", "Y"],
            listb = ["A", "B"];
    
        for (var i = 0; i < lista.length; i++) {
            document.write(lista[i]);
            for (var j = 0; j < listb.length; j++) {
                if (listb[j] == lista[i]) {
                    document.write(" common");
                    break;
                }
            }
            document.write("<br/>");
        }
    }