-1

I'm trying to get the highest key and value from an object, how can I return the desired result?

Here's my object:

categories = {
            'personal' : 4,
            'swag' : 3,
            'mingle' : 2,
            'attention' : 1
};

Desired functionality:

returnMax(categories) // {personal : 4}
5
  • 1
    Define "highest". How is personal: 4 the highest? Just because it was coded first? Javascript has no order of properties. stackoverflow.com/questions/5525795/…
    – Jonathan M
    Nov 4, 2014 at 23:26
  • 2
    Have you tried to implement and algorithm yourself? By that I mean what have you already tried between the braces of returnMax?
    – robbmj
    Nov 4, 2014 at 23:27
  • Hey, Yes i'm trying to write my own function but it's not working. Is there any functions that have been already created?
    – user990717
    Nov 4, 2014 at 23:33
  • You can post your own function code, and we can help :) But if you don't mind using a library, you can use lodash or underscore's max function (lodash.com/docs#max or underscorejs.org/#max) Nov 4, 2014 at 23:35
  • I tried underscore but it only returns the value and not the associated key.
    – user990717
    Nov 4, 2014 at 23:56

2 Answers 2

1

Here is how I would do it: http://jsfiddle.net/nwj7sad1/5/

categories = {
    'personal' : 4,
    'swag' : 3,
    'mingle' : 2,
    'attention' : 1
};


console.log(MaxCat(categories));

function MaxCat(obj){
    var highest = 0;
    var arr = [];
    for (var prop in obj) {
        if( obj.hasOwnProperty( prop ) ) {
            if(obj[prop] > highest ){ 
                arr = [];
                highest = obj[prop];
                arr[prop] = highest;
            }

        } 
    }
    return arr;
}
0
0

For these types of things I like to write my own algorythms. Here is one I quickly wrote up:

function highest(o){
    var h = undefined;

    for(var key in o){
        var current = o[key];

        if(h === undefined || current > h){
            h = current;
        }
    }

    return h;
}

JSFiddle

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.