Get the highest value in object

337
November 22, 2016, at 1:39 PM

I have an object like so:

var lookup = {
    42: "42", 
    43: "43"
}

How can I get the highest value in this object? I am expecting to get 43 because it's the highest number.

Answer 1

As the comments indicate, your question is a bit vague. If you're looking to compare the string values parsed as ints, the following should work based on your object's structure:

var myArray = Object.keys(lookup).map(function(current){ 
    return parseInt(current)
});
var max = Math.max.apply(null, myArray)
Answer 2

Try this function:

function getMax(dataObj){
var max;
for(var key in dataObj){
     if (dataObj.hasOwnProperty(key)) {
        var number = parseFloat(dataObj[key]);
        //max by default is undefined and number could be NaN 
        if(!max && number){ 
            max = number;
        }
        else if(number > max){
            max = number;
        }
    }
}
return max;
}

It will loop through an object and get all the properties set on this object (not in the prototype chain), try to convert them to number and then return the max. Note this is not returning the key, but rather the value.

Answer 3

For the sake of having a diversity of answers, here's a more functional implementation using lodash's reduce and a ternary operator:

_.reduce(_.values(lookup), function(max, n){ return n > max ? n : max; });
READ ALSO
How to return the table with javascript or jquery by returning another table with all the rows that contains a td that doesn't have a colspan

How to return the table with javascript or jquery by returning another table with all the rows that contains a td that doesn't have a colspan

How to return the table with javascript or jquery by returning another table with all the rows that contains a td that doesn't have a colspan.

233
Run JS function after delay after page is loaded

Run JS function after delay after page is loaded

So I am running a very simple function atm that runs on page load. However whilst the page has finished loading, it sometimes takes half a second or so for the content itself to actually pop up.

330
jquery mobile send value in link and get in multipages file

jquery mobile send value in link and get in multipages file

I want to use a single file with multiple pages. [nnn]In the #first page I have a link to another page with a value sent via GET:.

393
How to start with Custom Chart

How to start with Custom Chart

I want to create this CHART, but i don't know how to start with that. .

351