1

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.

4
  • 1
    Loop through the keys, and compare the values (keep track of the lowest value)? Commented Jul 29, 2012 at 22:35
  • What about the case where different "keys" have the same smallest value? Let's say thingD : 5 for instance. Is it possible? In that case, what should be the expected result? Commented Jul 29, 2012 at 22:51
  • @ZER0 Good question! In this case it doesn't matter; any result key will do if it has the smallest value. Commented Jul 30, 2012 at 8:09
  • In that case one of the @minitech answers is good enough. Commented Jul 30, 2012 at 8:34

2 Answers 2

2

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]
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! I have never really used the map.reduce pattern before so I am going to take some time to learn it.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.