Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding the max value of an attribute in an array of objects and return the entire object

Tags:

javascript

I know a similar question has been asked here: Finding the max value of an attribute in an array of objects, but with that method there is no way to return the entire object containing the maximum.

I have this array of objects:

[
 {Prop: "something", value: 2},
 {Prop: "something_else", value: 5},
 {Prop: "bla", value: 3}
]

I want to find the maximum value over the property "value" and then I want to return the entire object

{Prop: "something_else", value: 5}

What is the easiest way to do that in javascript?

like image 780
valenz Avatar asked Dec 03 '25 17:12

valenz


2 Answers

The easiest way is to do this with reduce(). We can handle this in the minimum amount of steps needed, simply replacing the previous value if the current element's value is greater than the previous:

const objs = [
 {Prop: "something", value: 2},
 {Prop: "something_else", value: 5},
 {Prop: "bla", value: 3}
];

const maxObj = objs.reduce((p, c) => p.value > c.value ? p : c);

console.log(maxObj);

Don't sort your array! The main issue with sorting an array, is it causes many needless iterations through. This gets drastically slower the bigger your array is, sorting to try and move elements up and down.

like image 174
ugh StackExchange Avatar answered Dec 06 '25 08:12

ugh StackExchange


Could also use something like Array.prototype.reduce.

i.e.

function maxVal(arr) {
    return arr.reduce(function (prev, curr) {
        return (prev.value >= curr.value) ? prev : curr;
    });
}

EDIT: If you want a basic way of doing it, simply by iterating through the array, you can do something like:

function maxVal(arr) {
    var max = arr[0];
    for (var i = 1, iMax = arr.length; i < iMax; i++) {
        if (max.value < arr[i].value) {
            max = arr[i];
        }
    }
    return max;
}
like image 30
boxsome Avatar answered Dec 06 '25 06:12

boxsome