Using info returned from an API in the form of JSON, I am trying to manipulate the following data:

"results": [
    {
        "url": "etcetc",
        "id": 1,
        "user": {
            "url": "etcetc",
            "id": 2,
            "email": "[email protected]",
            "username": "example",
            "first_name": "mister",
            "last_name": "sample"
        },
        "data1": "String",
        "data2": 10,
        "data3": 6,
        "data4": 12000,
        "data5": 0.3333333333333333
    }

so there are several objects returned under "results", and each object has its own set of data1-5. Using Angular, what is the best way to search for the object with the highest data5, and return the rest of the info for that particular object? So I'd print out data1-5 for the array object with the highest data5 value, if that makes sense.

share|improve this question
up vote 4 down vote accepted

Assuming you have an object, not JSON, or parse the JSON into an object, you can use Array.reduce

var max = obj.results.reduce(function(a,b) {
    return a.data5 > b.data5 ? a : b;
});

FIDDLE


ES2015 version

var max = obj.results.reduce( (a, b) => a.data5 > b.data5 ? a : b );
share|improve this answer

A simple for-each loop is all you need:

highest = results[0]  // seed highest with the first element

results.forEach(function(el) {
  if (el['data5'] > highest['data5'])
    highest = el
})
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.