我有以下代码来计算我的值集中的最高值:
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;
但是我测试了它并且没有用,你可以帮助我吗?
答案 0 :(得分:2)
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
属性,您需要获取该对象数组中的最低值和最高值,这样就可以了:< / p>
// 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);
答案 1 :(得分:0)
使用ES5:
let 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.apply(Math,vals);
component.props.maxRange = Math.max.apply(Math,vals);
console.log(component.props.minRange, component.props.maxRange);