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!
CodePudding user response:
just add break the first time it met the condition.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/break
const numbers = [0.4,0.6];
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);
break;
}
}
}