Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find object having maximum value for the `id` property in an array of objects

Tags:

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.

like image 260
Krishanu Dey Avatar asked Mar 28 '14 12:03

Krishanu Dey


People also ask

How do you find the maximum INT of an array?

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.

What is the maximum value of an array?

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 .


2 Answers

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'} 
like image 65
mbcrute Avatar answered Oct 05 '22 23:10

mbcrute


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  
like image 42
AbolfazlR Avatar answered Oct 05 '22 23:10

AbolfazlR