Yamaha32088
Yamaha32088

Reputation: 4163

Returning largest value in javascript object

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?

Upvotes: 1

Views: 719

Answers (1)

Oriol
Oriol

Reputation: 288080

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.

Upvotes: 3

Related Questions