In my array of objects, I want to find the object with the highest value for the id
property.
Here is my array:
myArray = [ { 'id': '73', 'foo': 'bar' }, { 'id': '45', 'foo': 'bar' }, // … ];
Generally, I use $.grep
to find values in an array, like this:
var result = $.grep(myArray, function (e) { return e.id == 73; });
But in this case I need to provide a specific id
value for the object I want to select.
For unsorted array, you can initialize a maximum number variable with value 0 (given the array is made of positive values) then iterate over all the items in the array assigning the larger number at each iteration to the maximum variable.
M = max( A ) returns the maximum elements of an array. If A is a vector, then max(A) returns the maximum of A . If A is a matrix, then max(A) is a row vector containing the maximum value of each column of A .
The question states that he wants to find the object with the greatest id, not just the greatest id...
var myArray = [{'id':'73','foo':'bar'},{'id':'45','foo':'bar'}]; var max = myArray.reduce(function(prev, current) { if (+current.id > +prev.id) { return current; } else { return prev; } }); // max == {'id':'73','foo':'bar'}
const students = [ { id: 100, name: 'Abolfazl', family: 'Roshanzamir' }, { id: 2, name: 'Andy', family: 'Madadian' }, { id: 1500, name: 'Kouros', family: 'Shahmir' } ]
If you want to find the object with max Id :
const item = students.reduce((prev, current) => (+prev.id > +current.id) ? prev : current) // it returns { id: 1500, name: 'Kouros', family: 'Shahmir' }
If you want to find the object with min Id :
const item = students.reduce((prev, current) => (+prev.id < +current.id) ? prev : current) // it returns {id: 2, name: "Andy", family: "Madadian"}
If you wnat to find the max Id :
const max = Math.max.apply(null, students.map(item => item.id)); // it returns 1500
If you want to find the min Id :
const min = Math.min.apply(null, students.map(item => item.id)); // it returns 2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With