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

JavaScript如何截取数组中首个符合条件元素及后续所有元素

从房屋数组中获取第一个可用元素开始的后续所有元素

需求说明

获取房屋对象数组中,从第一个available属性为true的元素开始的所有后续元素,后续元素无论available是否为true都保留。

示例输入

{
  "houses": [
    { "available": false, "price": "80000" },
    { "available": false, "price": "700000" },
    { "available": true, "price": "8120000" },
    { "available": false, "price": "120000" },
    { "available": true, "price": "340000" }
  ]
}

期望输出

{
  "houses": [
    { "available": true, "price": "8120000" },
    { "available": false, "price": "120000" },
    { "available": true, "price": "340000" }
  ]
}

代码分析与优化

你编写的代码逻辑完全可以实现需求:

const firstAvailableHouseIndex = houses.findIndex(house => house.available === true);
const housesStartingFromFirstAvailable = houses.filter((house, index) => index >= firstAvailableHouseIndex);
  • findIndex会返回第一个available为true的元素索引,若找不到符合条件的元素则返回-1
  • filter通过索引判断,筛选出从该位置开始的所有元素

如果想让代码更高效,可以用数组的slice方法替代filter,它直接截取数组的指定片段,无需遍历所有元素做索引判断:

const firstAvailableHouseIndex = houses.findIndex(house => house.available === true);
const housesStartingFromFirstAvailable = houses.slice(firstAvailableHouseIndex);

边界情况处理

如果数组中没有任何available为true的元素,findIndex会返回-1,此时slice(-1)会返回数组最后一个元素。若需要这种场景返回空数组,可以补充判断:

const firstAvailableHouseIndex = houses.findIndex(house => house.available === true);
const housesStartingFromFirstAvailable = firstAvailableHouseIndex !== -1 
  ? houses.slice(firstAvailableHouseIndex)
  : [];

内容的提问来源于stack exchange,提问作者Zeusox

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 19:45:51