Find the object with the maximum value for id in the javascript object array

Here is my array

myArray = [{'id':'73','foo':'bar'},{'id':'45','foo':'bar'},etc.]

I want to find an object by id in the above javascript object array.

I usually use grep()to search in an array like this

var result = $.grep(myArray, function(e){ return e.id == 73; });

But in this case, I need to specify the ID value that I want to select.

+4
source share
4 answers
myArray = [{'id':'73','foo':'bar'},{'id':'45','foo':'bar'}];

var maxid = 0;

myArray.map(function(obj){     
    if (obj.id > maxid) maxid = obj.id;    
});


alert(maxid);

This will give you the maximum id of the objects in the array.

Then you can use grep to get the related object:

var maxObj = $.grep(myArray, function(e){ return e.id == maxid; });
+7
source

The question says that he wants to find the object with the largest id, and not just the largest 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'}
+6
source
var max = 0;
var myArray = [{'id':'73','foo':'bar'},{'id':'45','foo':'bar'}]
var maxEle = myArray.map(function(ele){ if(ele.id>max){ max=ele} });

map is a function that iterates through array elements and performs a specific operation.

+1
source
function reduceBy(reducer, acc) {
    return function(by, arr) {
        return arr[arr.reduce(function(acc, v, i) {
            var b = by(v);
            return reducer(acc[0], b) ? [b, i] : acc;
        }, acc || [by(arr[0]), 0])[1]];
    };
}
var maximumBy = reduceBy(function(a,b){return a<b;});


var myArray = [{'id':'73','foo':'bar'},{'id':'45','foo':'bar'}];
console.log(maximumBy(function(x){
    return parseInt(x.id,10)
}, myArray)); // {'id':'73','foo':'bar'}
0
source

Source: https://habr.com/ru/post/1533906/


All Articles