7

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?

5
  • 1
    Why is data an object and not an array or at least array-like object? Commented Apr 15, 2013 at 11:09
  • @FelixKling it is a JSON object passed from a PHP script. I force an object for other purposes :) Commented Apr 15, 2013 at 11:17
  • What is wrong with looping over the object members? That seems pretty simple, maintainable and very compatible to me. Commented Apr 15, 2013 at 11:22
  • @RobG Absolutely nothing wrong with it, but I just wanted to check there were not any javascript functions already there that would make the process simpler :-) Commented Apr 15, 2013 at 11:23
  • I don't see how nesting 3 functions is simpler that basic loop. A little less code perhaps, but certainly not simpler. Performance seems mixed, it doesn't seem any faster on balance. Commented Apr 15, 2013 at 11:38

2 Answers 2

17

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']; })); 
Sign up to request clarification or add additional context in comments.

2 Comments

It will need shims for missing ES5 features like Object.keys and map.
How can I return the index of the item with the highest number?
0

You can create your own (for) loop and return the max value that way. Another option is to use a library like Underscore.js to handle this for you and keep your code readable.

3 Comments

Okay, thank you. So, in short, without a plugin there is no short easy way, I need to loop through as I suggested in my question?
Well...a plugin will also loop through the object/array internally. There is no other solution.
Thought so :-). I have accepted @Zapshu's solution as it provides exactly what I am looking for. Thanks anyway

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.