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?
This is more better solution
You can use built-in Array object to use Math.max/Math.min instead:
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:
...or you can define that inner function with ES6 function syntax:
If you want to be cute you can attach this to array:
Now you can just say:
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:
1, native java-script way
2, first sort object then it easy to get min max from sorted obj
Another one, similar to Kennebec's answer, but all in one line:
for Max
for min