Compare JavaScript Array of Objects to Get Min / Max Compare JavaScript Array of Objects to Get Min / Max arrays arrays

Compare JavaScript Array of Objects to Get Min / Max


The reduce is good for stuff like this: to perform aggregate operations (like min, max, avg, etc.) on an array of objects, and return a single result:

myArray.reduce(function(prev, curr) {    return prev.Cost < curr.Cost ? prev : curr;});

...or you can define that inner function with ES6 function syntax:

(prev, curr) => prev.Cost < curr.Cost ? prev : curr

If you want to be cute you can attach this to array:

Array.prototype.hasMin = function(attrib) {    return (this.length && this.reduce(function(prev, curr){         return prev[attrib] < curr[attrib] ? prev : curr;     })) || null; }

Now you can just say:

myArray.hasMin('ID')  // result:  {"ID": 1, "Cost": 200}myArray.hasMin('Cost')    // result: {"ID": 3, "Cost": 50}myEmptyArray.hasMin('ID')   // result: null

Please note that if you intend to use this, it doesn't have full checks for every situation. If you pass in an array of primitive types, it will fail. If you check for a property that doesn't exist, or if not all the objects contain that property, you will get the last element. This version is a little more bulky, but has those checks:

Array.prototype.hasMin = function(attrib) {    const checker = (o, i) => typeof(o) === 'object' && o[i]    return (this.length && this.reduce(function(prev, curr){        const prevOk = checker(prev, attrib);        const currOk = checker(curr, attrib);        if (!prevOk && !currOk) return {};        if (!prevOk) return curr;        if (!currOk) return prev;        return prev[attrib] < curr[attrib] ? prev : curr;     })) || null; }


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 Infinityvar 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);


Use sort, if you don't care about the array being modified.

myArray.sort(function (a, b) {    return a.Cost - b.Cost})var min = myArray[0],    max = myArray[myArray.length - 1]