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.