[英]how to use promise function in javascript functional function like forEach reduce?
[英]how to use the reduce function JavaScript
我们如何从对象数组中获取最小值?
const arr = [
objTemp1 = {value: 10},
objTemp2 = { value: 1},
objTemp3 ={value: 40}
]
function smalels(...obj) => obj.reduce(initial_value, value){
if (initial_value < value)
return initial_value
else
return value } )
我在哪里做错了?
通过拥有一个对象数组,您可以直接减少这个数组并返回具有最小值的 object。
const array = [{ value: 10 }, { value: 1 }, { value: 100 }], result = array.reduce((a, b) => a.value < b.value? a: b); console.log(result);
@Derek.W 回答得很好。 我的解决方案也是一样的。
objTemp1 = {
value: 10,
};
objTemp2 = {
value: 1,
};
objTemp3 = {
value: 100,
};
var allObj = [objTemp1,objTemp2,objTemp3]; //I took all the objects in an array
var smallestObj = allObj.reduce((prev,currentValue)=>{
return prev.value <= currentValue.value ? prev : currentValue;
});
您可以使用Array.reduce
获取最小值 object,如下所示。
const objTemp1 = { value: 10, }; const objTemp2 = { value: 1, }; const objTemp3 = { value: 100, } function smallest() { return Object.values(arguments).reduce((acc, cur) => { return (acc && acc.value < cur.value)? acc: cur; }, null); } console.log(smallest(objTemp1, objTemp2, objTemp3));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.