Home > Blockchain >  why JavaScript is behaving differently
why JavaScript is behaving differently

Time:02-28

why it is showing me 36 even though the minimum number is 27

   var combination = [27, 36]
    
    for (let x in combination) {
        if (combination[x] < 50) {
            var min = Math.min(combination[x])
        }
    }
    
    console.log(min)

i tried this multiple ways like

    var combination = [27, 30, 40, 44, 3, 239, 329, 2, 5, 20923, 96]
    
    for (let x in combination) {
        if (combination[x] < 50) {
            var min = Math.min(combination[x])
        }
    }
    
    console.log(min) //output--  5         //it should be 2

in this third example i add (-) to 2

var combination = [27, 30, 40, 44, 3, 239, 329, -2, 5, 20923, 96]

for (let x in combination) {
    if (combination[x] < 50) {
        var min = Math.min(combination[x])
    }
}

console.log(min) // output-- still 5     // it should be -2 

again when am adding (-) to other numbers like in -96 or -5 the output was okay (-96) but when im adding (-) to 2 it is not showing me -2 in the output instead it showing me 5

not only in javascript i tried this with lua, php but output was same as js

can anyone explain me why this happen and how solve this

CodePudding user response:

You're not comparing values to determine the minimum, but instead just replacing the min variable with the last number in the array that is smaller than 50. This can be fixed as follows:

let min = undefined;
for (let x in combination) {
    if (combination[x] < 50) {
        min = min == undefined ? combination[x] : Math.min(min, combination[x])
    }
}

Using filter and reduce, this can be made a lot shorter:

combination.filter(x => x < 50).reduce((x, y) => Math.min(x, y))
  • Related