如何筛选JS数组中从头至首次匹配'red'值前的所有元素
JavaScript数组按条件截取实现方案
实现思路
我们可以通过两步完成需求:
- 查找第一个
type字段值为'red'的元素的索引位置 - 用数组
slice方法截取从开头到该索引位置的子数组(slice为左闭右开特性,天然不会包含命中的red元素)
完整实现代码
// 修正原数组语法错误:对象属性之间添加逗号 const arrayFull = [ {id:'1', type:'blue'}, {id:'2', type:'blue'}, {id:'3', type:'blue'}, {id:'4', type:'blue'}, {id:'5', type:'red'}, {id:'6', type:'blue'}, {id:'7', type:'blue'}, {id:'8', type:'blue'}, {id:'9', type:'red'}, {id:'10', type:'red'}, ]; // 查找第一个type为red的元素索引 const firstRedIndex = arrayFull.findIndex(item => item.type === 'red'); // 截取数组,未找到red元素时返回整个原数组 const result = firstRedIndex === -1 ? [...arrayFull] : arrayFull.slice(0, firstRedIndex); console.log(result);
输出结果
[ {id:'1', type:'blue'}, {id:'2', type:'blue'}, {id:'3', type:'blue'}, {id:'4', type:'blue'} ]
兼容旧环境实现方案
如果需要兼容不支持findIndex的旧JS运行环境,可以用普通循环实现:
const result = []; for (let i = 0; i < arrayFull.length; i++) { if (arrayFull[i].type === 'red') break; result.push(arrayFull[i]); }
内容的提问来源于stack exchange,提问作者Agamem
相关产品推荐
相关产品推荐

