Output only one possible result looping thru 2 arrays with if-statement

Viewed 45

I have two arrays. Each element of which I compare numbers of first array are greater than the seconds' and if it finds (through if statement) any number from first array greater than any number from second array, I console.log them. However, there might be more than one coincidence but per one request in need to console.log only first result.

Say, First array has [0.4,0,6] Second array has [0.5,0.5]

It produces 2 results since there are two matches. How to get only first one.

My code looks like that:

https://jsfiddle.net/oxpwb0j3/2/

const numbers = [0.6,0.4];

for(a = 0; a < numbers.length; a++) {
     var res_num1 = numbers[a];
   
   const numbers2 = [0.5,0.5];
   
   for(b = 0; b < numbers2.length; b++) {
         var res_num2 = numbers2[b];
       
       if(res_num1 > res_num2){
            console.log(res_num1+" = "+res_num2);
       }
   }
}

it outputs:

0.6 = 0.5
0.6 = 0.5

as I explained in the beginning how to limit to only log the first result like so 0.6 = 0.5.

I'm new to JS and learning. Thank you!

2 Answers

Try to use labels

const numbers = [0.4,0.5,0.6];

   for(a = 0; a < numbers.length; a++) {

     var res_num1 = numbers[a];

     const numbers2 = [0.5,0.5];
     
     outerloop: for(b = 0; b < numbers2.length; b++) {

          var res_num2 = numbers2[b];

          if(res_num1 > res_num2){

            console.log(res_num1+" = "+res_num2);
            break outerloop;
          }
       }
   }

Related