Find the largest id in an array using $ .each

[{"id":1},{"id":2},{"id":3}] 

I know that I can use max, like this var most = Math.max.apply (Math, myArray) (if I have my array similar to this [1,2,3] ), but since I need to iterate over the list I'm just wondering if you can use a loop to get the greatest number;

 $.each(function(){ //this.id // how to continue here? }); 
+4
source share
2 answers

You can still use the Math.max.apply construct. Just use map to create an array of identifiers from objects:

 var maxId = Math.max.apply(Math, myList.map(function(o){ return o.id })); 
+6
source

Using $ .each

 var items = [{ "id": 2 }, { "id": 1 }, { "id": 3 }]; var maxId = Number.MIN_VALUE; $.each(items, function (index, item) { maxId = Math.max(maxId, item.id); }); 

Using ES5 for Each

 var maxId = Number.MIN_VALUE; items.forEach(function (item) { maxId = Math.max(maxId, item.id) }); 

Using ES5 reduces

 var maxId = items.reduce(function (maxId, item) { return Math.max(maxId, item.id) }, Number.MIN_VALUE); 

Using Underscore.js

Underscore.js has max , which also works in older browsers:

 var maxId = _.max(items, function (item) { return item.id }).id; 
+2
source

All Articles