-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}
David says reinstate Monica
  • 230,743
  • 47
  • 350
  • 385
user990717
  • 460
  • 8
  • 17
  • 1
    Define "highest". How is `personal: 4` the highest? Just because it was coded first? Javascript has no order of properties. http://stackoverflow.com/questions/5525795/does-javascript-guarantee-object-property-order – Jonathan M Nov 04 '14 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 04 '14 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 04 '14 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 (https://lodash.com/docs#max or http://underscorejs.org/#max) – trekforever Nov 04 '14 at 23:35
  • I tried underscore but it only returns the value and not the associated key. – user990717 Nov 04 '14 at 23:56

2 Answers2

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;
}
Noah Huppert
  • 3,248
  • 6
  • 30
  • 52
Edward
  • 2,931
  • 4
  • 28
  • 48
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

Noah Huppert
  • 3,248
  • 6
  • 30
  • 52