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

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'}

Leave a Comment