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

前端 未结 5 1753
暗喜
暗喜 2021-01-22 12:04

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 con

5条回答
  •  轮回少年
    2021-01-22 12:55

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

提交回复
热议问题