简体   繁体   中英

Find minimum value in javascript?

I want to print the minimum variable 'name' in JS. Currently it prints the minimaum value. I rather want the variable name. For eg:- In the current code, it gives me 4 , but I want c . How can I do this?

<script>
function myFunction()
{
var a = 5;
var b =10;
var c = 4;
document.getElementById("demo").innerHTML=Math.min(a,b,c);
}
</script>

Working DEMO

This should do the trick:

//Push values to object
var age = {};
age.a = 5;
age.b = 10;
age.c = 4;

var min = Infinity, name;

// Loop through object to get min value and then find relevant name
for(var x in age) {
    if( age[x] < min) {
        min = age[x];
        name = x;
    } 
}

console.log ( 'property name is ' + name + ' and value is ' + min );

Store the values in an array of objects. Each object will contain a name and value property. Then just iterate through the values and store the lowest.

var values = [
    {
       "name": "a",
       "value": 5
},
    {"name":"b",
      "value":10
    },
    {
        "name":"c",
        "value":4
    }
];

function min(arr){
    var minValue = {};
    for(var x = 0; x < arr.length; x++){
        if(arr[x].value < minValue.value || !minValue.value){
            minValue = arr[x];
        }
    }
    return minValue.name;
};
document.getElementById("demo").innerHTML = min(values);

JS Fiddle: http://jsfiddle.net/AgMbW/

You could put your values in an array like

var values = [
    { name: 'a', value: 5 },
    { name: 'b', value: 10 },
    { name: 'c', value: 4 }
 ];

and then use the filter method with the hint from Ahmad's comment :

var min_value = Math.min.apply(null, values.map(function(item) {
    return item.value;
}));

var min_name = values.filter(function (item) {
    return item.value == min_value;
})[0].name;

See this fiddle for a working example.

You can do this way:

var obj = {"names":["a","b","c"], "values":[5,10,4]}

var min = Math.min.apply( Math, obj["values"] );
var result = obj["names"][obj["values"].indexOf(min)];
document.getElementById("demo").innerHTML=result;

Here the fiddle: http://jsfiddle.net/eUcug/

Way 1 :

var x = 5;var getName = function(value){if(value === 5) return 'x'; else return null}

Way 2 : NameValue.getName = function(value){for(i = 1;i<=2;i++){if(this["val" + i].value === value) {return this["val" + i].name;break;}console.log(this["val" + i]);}return null;}NameValue.val2 = {name : 'y',value : 1};NameValue.prototype.add({name : 'x',value : 10})

NameValue.getName(10);  //return "x"

I hope you can understand how to find the variable name.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM