You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何筛选JS数组中从头至首次匹配'red'值前的所有元素

JavaScript数组按条件截取实现方案

实现思路

我们可以通过两步完成需求:

  1. 查找第一个type字段值为'red'的元素的索引位置
  2. 用数组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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 19:15:00