我有以下代码来计算我的一组值中的最高值:
var collection = [];
$histogram.find('li').each(function() {
collection.push($(this).data());
});
component.props.collection = collection;
// Find Histogram max value
collection.hasMax = function(value) {
return this.reduce(function(prev, curr) {
return prev[value] > curr[value] ? prev : curr;
});
};
// Assign Max Value
component.props.maxRange = collection.hasMax('value').value;
我需要创建第二个函数来执行相同的操作,但针对最低值,例如名为 hasMin
的函数。我认为只需更改此处的比较就足够了:
return prev[value] < curr[value] ? prev : curr;
但是我测试了它,但它不起作用,你能帮我吗?
最佳答案
JavaScript 的内置 Math
对象有一个静态 Math.min()
方法,这似乎可以解决您的问题,而不需要您正在使用的所有代码。
您可以使用 JavaScript 的 destructuring assignment 获取数组的最小值。 (将数组转换为逗号分隔的值列表)并将该列表传递给该方法。
还有Math.max()
。
let myData = [1,2,3,4,5,6,7,8,9,10];
console.log(Math.min(...myData));
console.log(Math.max(...myData));
您已经指出 collection
是一个对象数组,每个对象都有一个 value
属性,您需要获取该对象数组中的最低值和最高值,以便这样就可以了:
// This is just set up to emulate your data structure. Don't add this:
var sth = "test", sth2 = "test", sth3 = "test";
let component = { props: {} };
let collection = [{value:0, label: sth},{value:1, label: sth2},{value:3, label:sth3}];
// Assuming your data structure is set up, the following will get you there:
// Loop over the array of objects, extracting the value property of each object into a new array
let vals = collection.map(function(obj){
return obj.value; // Place the value of each object into an array
});
// Just set your object's properties to the min and max of the destructured array
component.props.minRange = Math.min(...vals);
component.props.maxRange = Math.max(...vals);
console.log(component.props.minRange, component.props.maxRange);
关于javascript - 如何在 JS 中找到数组中的最小值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49982157/