2

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.

2 Answers 2

4

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

Comments

0

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
})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.