我是 JS 的新手,第一次接触这里。
如何在 array.reduce 中返回一个对象?
例如:我想找到给定日期数据集的最低价(我使用货币 API 作为一个有趣的数据集来玩)。我得到的数据是一个对象数组。所以我每天都在使用 reduce 进行迭代并找到最低点。
const lowestLow = historialCandlesFloatData.reduce((lowestLow,currentDay) => {
if(currentDay.l < lowestLow.l){
return lowestLow = currentDay;
}else return lowestLow;
},);
这很好用,但我还需要返回最低的对象索引。现在我知道您可以将索引用作 reduce 的一部分,并且我可以 console.log 最低低点是什么索引,但我不知道如何将它与低点一起作为对象返回?
我可以只使用 forEach,这似乎工作正常,但这似乎不是最好的方法,我真的很想知道!
const findLow = ()=>{
let currentDayLow = 2;
let dataIndex = 0;
let datavalue = 0;
historialCandlesFloatData.forEach((day)=>{
if(day.l < currentDayLow){
currentDayLow = day.l;
datavalue = dataIndex;
}
dataIndex ++;
});
return {
lowestLow: currentDayLow,
indexValue: datavalue,
}
}
最佳答案
如果除了数组中的一个值之外,您还需要其他任何东西,您将受益于使用 reduce
的第二个参数:累加器的 initial 值。在这种情况下,累加器将是当前“最佳”索引,因此累加器初始值可以为 0。
注意:您可以使用条件运算符代替 if else
。
const lowestIdx = historialCandlesFloatData.reduce((lowestIdx, currentDay, i) => {
return currentDay.l < historialCandlesFloatData[lowestIdx].l
? i
: lowestIdx;
}, 0); // Initial index
然后使用该索引,您可以检索相应的对象
const lowest = historialCandlesFloatData[lowestIdx];
关于javascript - 如何返回 array.reduce 中的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73182624/