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?
The fastest way, in this case, is looping through all elements, and compare it to the highest/lowest value, so far.
(Creating an array, invoking array methods is overkill for this simple operation).
I think Rob W's answer is really the right one (+1), but just for fun: if you wanted to be "clever", you could do something like this:
or if you had a deeply nested structure, you could get a little more functional and do the following:
These could easily be curried into more useful/specific forms.
Use
Math
functions and pluck out the values you want withmap
.Here is the jsbin:
https://jsbin.com/necosu/1/edit?js,console
UPDATE:
If you want to use ES6:
Using Array.prototype.reduce(), you can plug in comparator functions to determine the min, max, etc. item in an array.
This can be achieved with lodash's
minBy
andmaxBy
functions.Lodash's
minBy
andmaxBy
documentationSolution
Use
sort
, if you don't care about the array being modified.