Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return Maximum value from a JSON Object

Tags:

javascript

max

I have an associative array which looks like:

var data = {
    0: {
        'Number_of_Something': 212
    },
    1: {
        'Number_of_Something': 65
    },
    2: {
        'Number_of_Something': 657
    }
}

I need to extract the highest value in the field Number_of_Something, however, because it is a field within an object of an object, it is a little more complicated than just following a similar method to something outlined here.

Looping through the object and storing the value, then replacing it if the next one is larger seems like the easiest and obvious option.

I am simply asking this question in case there is a simpler (smarter) way of achieving this other than the method outlined above?

like image 490
Ben Carey Avatar asked Apr 15 '13 11:04

Ben Carey


People also ask

What is the maximum number of key value pairs that JSON supports?

So the limit is (2^32)-1 or 4294967295 if adhering to the spec.

Can JSON have a top level array?

Yes, an array is legal as top-level JSON-text.


1 Answers

simpler can be subjective... Another way to achieve what you ask is to get an array of the values using Object.keys and Array.prototype.map, and use the other solution with Math.max that you linked :

var data = {
    0: {
        'Number_of_Something': 212
    },
    1: {
        'Number_of_Something': 65
    },
    2: {
        'Number_of_Something': 657
    }
}

var max = Math.max.apply(null,
                        Object.keys(data).map(function(e) {
                                return data[e]['Number_of_Something'];
                        }));
like image 99
Cattode Avatar answered Oct 17 '22 22:10

Cattode