Stanislav Beremski
Stanislav Beremski

Reputation: 102

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 5 is the smallest value compared to the other key/value pairs.

Upvotes: 1

Views: 1014

Answers (2)

Ry-
Ry-

Reputation: 224983

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]

Upvotes: 2

spaceman12
spaceman12

Reputation: 1109

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 run
var obj={thingA:5,thingB:10,thingC:15};
var smallest=getSmallest(obj)//thingA:5

Upvotes: 1

Related Questions