简体   繁体   中英

Better way to get min value of specific Array property

I found a way to get the min value of a specific property in an array. It is a 2 step process. Is there a better, more direct way?

Goal: get the min Price value from array

Example:

array = [{"ID": 1, "Price": 2.30}, {"ID": 2, "Price": 3.00}, {"ID": 3, "Price": 1.75}];

Here's what I did:

Step 1: create temp array holding only the Price values

var filteredArray = array.map(function (val) {
                            return val["Price"];
                        });

Step 2: find the min Price value

var arrayMinValue = Function.prototype.apply.bind(Math.min, null);

var minPrice = arrayMinValue(filteredArray)

This seems to work. But is Step 1 needed? Is there a way to find the min Price value directly without using Step 1?

Thanks!

Perfect use case for Array.reduce() :

array.reduce((lowest, obj) => Math.min(obj.Price, lowest), Infinity)

If you're unfamiliar, see Mozilla's documentation , but in brief, the first argument is a callback whose first two params are 1) the running value that will eventually be returned at the end of execution and 2) each element from the input array. The second argument is the initial running value. The callback returns the new running value that will be passed in with the next array element.

Use Array#reduce method to reduce into a single value by iterating over the values.

 array = [{ "ID": 1, "Price": 2.30 }, { "ID": 2, "Price": 3.00 }, { "ID": 3, "Price": 1.75 }]; // iterate over the array elements var min = array.reduce(function(prev, next) { // return the minimum value return prev < next.Price ? prev : next.Price; // set initial value as infinity which is the highest possible value }, Math.infinity); console.log(min) 

You can use the Array.from method to create an array with the prices and the use of Math.min like:

 var arr = [{ "ID": 1, "Price": 2.30 }, { "ID": 2, "Price": 3.00 }, { "ID": 3, "Price": 1.75 }]; var minPrice = Math.min.apply(null, Array.from(arr, e => e['Price'])); console.log(minPrice) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM