Reputation: 23
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.
Upvotes: 2
Views: 85
Reputation: 318182
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;
});
ES2015 version
var max = obj.results.reduce( (a, b) => a.data5 > b.data5 ? a : b );
Upvotes: 4
Reputation: 42440
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
})
Upvotes: 0