问题描述:
如何在 array.reduce 中返回一个对象?
例如:我想找到给定日期数据集的最低点。(我使用货币 API 作为一个有趣的数据集来玩)。我得到的数据是一个对象数组。所以我每天都在使用 reduce 来迭代并找到最低的低点。
const lowestLow = historialCandlesFloatData.reduce((lowestLow,currentDay) => {
if(currentDay.l < lowestLow.l){
return lowestLow = currentDay;
}else return lowestLow;
},);
这很好用,但我还需要返回的对象的索引为最低值。现在我知道你可以使用索引作为reduce的一部分,我可以控制台记录最低低的索引是什么,但我不知道如何将它与低作为对象一起返回?
我可以只使用一个 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,您需要使用“累加器”来传递一个带有值和索引的对象。(呃,或者只是返回索引然后使用它来获取元素,如trincot 所示。)例如:
const lowestLow = historialCandlesFloatData.reduce((lowestLow, currentDay, index) => {
return !lowestLow || currentDay.l < lowestLow.entry.l ? { entry: currentDay, index } : lowestLow;
}, null)
或者,您可以通过向累加器添加索引来使累加器成为数组中对象的增强版本:
const lowestLow = historialCandlesFloatData.reduce((lowestLow, currentDay, index) => {
return !lowestLow || currentDay.l < lowestLow.l ? { ...currentDay, index } : lowestLow;
}, null);
但我不喜欢使用reducead hoc 函数,尤其是因为忘记提供种子值(必要时)、忘记在所有代码路径上执行等很容易绊倒它return。除非你'重新使用预定义的、可重用的 reducer 函数进行函数式编程,我更喜欢简单的循环:
let lowestLow = null;
let lowestIndex;
for (let index = 0; index < historialCandlesFloatData.length; ++index) {
const entry = historialCandlesFloatData[index];
if (!lowestLow || entry.l < lowestLow.l) {
lowestLow = entry;
lowestIndex = index;
}
}
是的,在这种情况下,它的代码更多,但您可能会发现它更清晰和/或更不容易出错,尤其是在您刚开始的时候。
解决思路二:
为什么不使用 JavaScript 的扩展运算符向对象添加新属性...
?例如,像这样:
const lowestLow = historialCandlesFloatData.reduce((lowestLow, currentDay, idx) => {
if(currentDay.l < lowestLow.l){
return {
...currentDay,
idx: idx,
};
} else {
return lowestLow;
}
},
// Initial value
{ l: historialCandlesFloatData[0].l + 1 }
);
// Now you can access the index like so
const index = lowestLow.idx;
解决思路三(这是解决小编问题的思路):
以上仅为部分解决思路介绍,请查看全部内容,请添加下方公众号后回复001,即可查看。公众号有许多评分最高的编程书籍和其它实用工具,绝对好用,可以放心使用
如果您觉得有帮助,可以关注公众号——定期发布有用的资讯和资源