如何在array.reduce中返回包含最低值及其索引的对象?
问题描述
我是JavaScript新手,首次提问。我通过货币API获取了一组对象数组形式的每日数据,想要找出其中最低的low值。目前我使用array.reduce实现了获取最低low值的功能,但还需要同时返回该值对应的索引。我知道reduce可以使用index参数,也能打印出索引,但不知道如何将其与最低值一起以对象形式返回。我能用forEach实现需求,但希望了解更合适的reduce写法。
现有代码示例
使用reduce的实现
const lowestLow = historialCandlesFloatData.reduce((lowestLow,currentDay) => { if(currentDay.l < lowestLow.l){ return lowestLow = currentDay; }else return lowestLow; },);
使用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的累加器返回一个包含最低值和对应索引的对象,而不是直接返回数组元素。具体实现如下:
const result = historialCandlesFloatData.reduce((acc, currentDay, index) => { // 处理第一个元素,初始化累加器 if (!acc) { return { lowestLow: currentDay.l, indexValue: index }; } // 比较当前值与累加器中的最低值,更新累加器 if (currentDay.l < acc.lowestLow) { return { lowestLow: currentDay.l, indexValue: index }; } // 当前值不更小,返回原累加器 return acc; }, null);
关键说明
- 累加器
acc是一个对象,包含lowestLow(当前最低的low值)和indexValue(对应索引)两个属性 - 初始值设为
null,确保第一个元素能正确初始化累加器 - 每次迭代对比当前元素的
l值与累加器中的最低值,仅当当前值更小时更新累加器 - 最终
result就是包含目标信息的对象,和你用forEach返回的结构一致
另外,你原来的reduce代码未设置初始值,数组为空时会抛出错误,上述写法加入初始值后鲁棒性更强。
内容的提问来源于stack exchange,提问作者The Hatchery
相关产品推荐
相关产品推荐

