javascriptarrayscomparearray-of-dict

Compare JavaScript Array of Objects to Get Min / Max


I have an array of objects and I want to compare those objects on a specific object property. Here's my array:

var myArray = [
    {"ID": 1, "Cost": 200},
    {"ID": 2, "Cost": 1000},
    {"ID": 3, "Cost": 50},
    {"ID": 4, "Cost": 500}
]

I'd like to zero in on the "cost" specifically and a get a min and maximum value. I realize I can just grab the cost values and push them off into a javascript array and then run the Fast JavaScript Max/Min.

However is there an easier way to do this by bypassing the array step in the middle and going off the objects properties (in this case "Cost") directly?


Solution

  • One way is to loop through all elements and compare it to the highest/lowest value.

    (Creating an array, invoking array methods is overkill for this simple operation).

     // There's no real number bigger than plus Infinity
    var lowest = Number.POSITIVE_INFINITY;
    var highest = Number.NEGATIVE_INFINITY;
    var tmp;
    for (var i=myArray.length-1; i>=0; i--) {
        tmp = myArray[i].Cost;
        if (tmp < lowest) lowest = tmp;
        if (tmp > highest) highest = tmp;
    }
    console.log(highest, lowest);