1

I am looking for a simple solution to find the largest integer in an object I have the following object named numberZeros

Object {0: 3, 1: 3, 3: 2, 4: 3, 5: 4, 6: 2, 7: 3, 8: 5}

Here is how I am trying to see which one has the largest value but it returns undefined.

Array.max = function( numberZeros ){
    console.log(Math.max.apply( Math, numberZeros));
};

I am guessing it is because it does not work on objects. How would I get it to return 8: 5?

1
  • 1
    You iterate manually. Commented Dec 8, 2013 at 0:51

1 Answer 1

3

The problem is that .apply needs an array instead of an object.

And in your case, you should could use an array instead of an object. (Edit: sorry I didn't see it was sparse)

But you can use

var obj = {0: 3, 1: 3, 3: 2, 4: 3, 5: 4, 6: 2, 7: 3, 8: 5},
    max = -Infinity;
for(var i in obj) {
    if(obj.hasOwnProperty(i)) {
        max = Math.max(max, obj[i]);
    }
}

But I think the following is better:

var arr = [3, 3,, 2, 3, 4, 2, 3, 5],
    max = Math.max.apply(null, arr);

It seems you want to get argmax instead of max. Then, use

var obj = {0: 3, 1: 3, 3: 2, 4: 3, 5: 4, 6: 2, 7: 3, 8: 5},
    max = -Infinity,
    argmax = void(0);
for(var i in obj) {
    if(obj.hasOwnProperty(i) && obj[i] >= max) {
        max = obj[i];
        argmax = i;
    }
}

or

var arr = [3, 3,, 2, 3, 4, 2, 3, 5],
    max = -Infinity,
    argmax = void(0);
for(var i=0, l=arr.length; i<l; ++i) {
    if(arr[i] >= max) {
        max = obj[i];
        argmax = i;
    }
}

Note: I have used >= in case all values in object/array are -Infinity, in order to have an argmax. If you are sure there will be at least one value greater than -Infinity, you can use < and gain some microseconds.

Sign up to request clarification or add additional context in comments.

6 Comments

I have to keep it as an object because of the index in front of the largest number
@megawac Good point, but not before ES5, so I'm not sure if it would work on all browsers.
@Yamaha32088 Then, do you want to get argmax instead of max?
I need it to return the exactly 8: 5 it cant just be 5 so if that is what argmax would do then yes
if you look closely at the object you see that it goes 1: 3, 3: 2 2 is not in there
|

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.