Skip to content Skip to sidebar Skip to footer

How To Find Minimum And Maximum Value In Object Literal By Javascript

I want to get minimum value from object literal and want to use it in anuglarjs i.e., :- scope.data = { 'studentName' : 'Anand', 'socialStudies' : '98', 'english' : '9

Solution 1:

Here's one way to do it that checks only numeric looking properties and returns both the max and min values and their corresponding property names (since I assume that would be useful to know):

scope.data = {
    'studentName' : "Anand", 
    'socialStudies' : "98",
    'english' : "90",
    'math' : "80"
};

function findMaxMin(obj) {
    var max = Number.MIN_VALUE, min = Number.MAX_VALUE, val;
    var maxProp, minProp;
    for (var prop in obj) {
        if (obj.hasOwnProperty(prop)) {
            val = +obj[prop];
            if (!isNaN(val)) {
                if (val > max) {
                    maxProp = prop;
                    max = val;
                }
                if (val < min) {
                    minProp = prop;
                    min = val;
                }
            }
        }
    }
    // if no numeric looking properties, then return nullif (!maxProp) {
        returnnull;
    }
    return {minVal: min, minProp: minProp, maxVal: max, maxProp: maxProp};
}

Working demo: http://jsfiddle.net/jfriend00/q81g6ehb/


And, if you want to use this on an array, you can just call it for each array element:

functionfindMaxMinArray(arr) {
    var results = [];
    for (var i = 0; i < arr.length; i++) {
        var m = findMaxMin(arr[i]);
        m.obj = arr[i];
        results.push(m);
    }
    return results;
}

Working demo: http://jsfiddle.net/jfriend00/uv50y3e8/


If you wanted it to auto-detect whether an array was past in or not and just always return an array of results, you could do this:

functionfindMaxMinAny(obj) {
    var results = [];
    if (Array.isArray(obj)) {
        for (var i = 0; i < arr.length; i++) {
            var m = findMaxMin(arr[i]);
            m.obj = arr[i];
            results.push(m);
        }
    } else {
        // only a single object
        results.push(findMaxMin(obj));
    }
    return results;
}

Solution 2:

Use jQuery.map() to translate items into new array, if the callback returns null or undefined that item will not be included. You can use that to filter the result ( for example, to remove the non numeric values ).

var data = {
    'studentName' : "Anand", 
    'socialStudies' : "98",
    'english' : "90",
    'math' : "80"
};

var array = $.map( data, function( val ) { 
    return $.isNumeric( val ) ? val : null; 
});

console.log( Math.max.apply( null, array ) ); // 98

Post a Comment for "How To Find Minimum And Maximum Value In Object Literal By Javascript"