Skip to content Skip to sidebar Skip to footer

How Do I Select A Key/value Pair By Finding The Smallest Value In A Number Of Key/value Pairs In A Javascript Object?

I have an object that looks like this: var obj = { thingA: 5, thingB: 10, thingC: 15 } I would like to be able to select the key/value pair thingA: 5 based on the fact that

Solution 1:

Nothing built-in does that, but:

var minPair = Object.keys(obj).map(function(k) {
    return [k, obj[k]];
}).reduce(function(a, b) {
    return b[1] < a[1] ? b : a;
});

minPair // ['thingA', 5]

Or, sans ECMAScript 5 extensions:

var minKey, minValue;

for(var x in obj) {
    if(obj.hasOwnProperty(x)) {
        if(!minKey || obj[x] < minValue) {
            minValue = obj[x];
            minKey = x;
        }
    }
}

[minKey, minValue] // ['thingA', 5]

Solution 2:

here is a simple function that can do exactly what you wanted -

function getSmallest(obj)
{
    var min,key;
    for(var k in obj)
    {
        if(typeof(min)=='undefined')
        {
            min=obj[k];
            key=k;
            continue;
        }
        if(obj[k]<min)
        {
            min=obj[k]; 
            key=k;
        }
    }
    return key+':'+min;
}



//test runvar obj={thingA:5,thingB:10,thingC:15};
var smallest=getSmallest(obj)//thingA:5

Post a Comment for "How Do I Select A Key/value Pair By Finding The Smallest Value In A Number Of Key/value Pairs In A Javascript Object?"