如何在JavaScript中使用filter同时获取对象数组的匹配数据与索引
用一次遍历同时获取filter匹配的对象与索引
你不用二次遍历数组,直接利用数组方法的回调参数就能在一次操作里拿到匹配对象和它的原数组索引,推荐用reduce方法实现,比先filter再查索引更高效:
示例实现
先定义你的对象数组:
const array = [ { number: 123, name: 'test1' }, { number: 1234, name: 'test14' }, { number: 1235, name: 'test15' }, { number: 1236, name: 'test16' } ];
情况1:可能有多个匹配项
用reduce遍历一次数组,收集所有符合条件的对象和对应索引:
const matchedItems = array.reduce((result, currentItem, currentIndex) => { if (currentItem.number === 1235) { result.push({ item: currentItem, index: currentIndex }); } return result; }, []); // 输出结果:[{ item: { number: 1235, name: 'test15' }, index: 2 }]
情况2:确定只有一个匹配项
如果能确定数组里只有一个符合条件的元素,可以直接拿到对应的对象和索引:
const { item, index } = array.reduce((matched, currentItem, currentIndex) => { if (currentItem.number === 1235) { return { item: currentItem, index: currentIndex }; } return matched; }, {}); // 此时item是匹配的对象,index是它在原数组的位置(2)
为什么不用filter?
filter方法的回调虽然也能拿到索引,但它只能返回原数组的元素,没法直接附加索引信息。如果硬要在filter里实现,需要给原对象临时加索引属性,这会修改原数据,反而麻烦。用reduce一次遍历就能完成条件判断和结果收集,逻辑更清晰,效率也更高。
内容的提问来源于stack exchange,提问作者simon nesk
相关产品推荐
相关产品推荐

