如何过滤含嵌套数组的二维数组并返回符合条件元素的索引?
修改代码返回符合条件元素的索引而非值
要实现返回pts数组中值大于等于20的元素对应的索引,只需调整数组处理逻辑,利用数组方法的索引参数收集符合条件的索引即可,原代码仅筛选了值,现在改成收集索引:
修改后的代码
const gp = [ [{ "pts": [10, 5, 40, 30, 95, 5, 11, 85] }, { "pts": [2, 1, 4] }, { "pts": [14, 22, 41, 23] }] ]; for (let n = 0; n <= 2; n++) { // 用reduce遍历数组,收集符合条件的索引 const race = gp[0][n].pts.reduce((indexList, value, index) => { if (+value >= 20) { indexList.push(index); } return indexList; }, []); if (race.length) { console.log(`race at n=${n}: ${race}`); }; };
逻辑说明
- 使用
Array.reduce遍历pts数组,回调函数可获取三个参数:累计结果数组、当前元素值、当前元素索引 - 判断当前值是否大于等于20,若是则将对应索引推入累计数组
- 最终累计数组就是所有符合条件的元素索引
运行结果
race at n=0: 2,3,4,7 race at n=2: 1,2,3
你也可以用map+filter的组合实现,效果一致:
const race = gp[0][n].pts .map((value, index) => +value >= 20 ? index : null) .filter(index => index !== null);
内容的提问来源于stack exchange,提问作者London28
相关产品推荐
相关产品推荐

