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

如何使用JavaScript移除数组中指定ID及后续的子数据

解决方案

实现思路

  1. 先遍历数组,找到**目标ID(需转成数字类型)**对应的元素位置
  2. 若找到该位置,截取数组从起始到该位置的前一个元素的片段;若未找到目标ID,返回原数组的浅拷贝

代码实现

const data = [
    {id: 1, name: 'Gill'},
    {id: 2, name: 'Gill2'},
    {id: 3, name: 'Gill3'},
    {id: 4, name: 'Gill4'},
    {id: 5, name: 'Gill5'}
];

function filterID(targetId, arr) {
    // 把字符串类型的目标ID转成数字,和数组里的id类型匹配
    const numId = Number(targetId);
    // 找到目标元素的索引
    const targetIndex = arr.findIndex(item => item.id === numId);
    // 若找到索引,截取0到该索引的部分;没找到则返回原数组的浅拷贝
    return targetIndex !== -1 ? arr.slice(0, targetIndex) : [...arr];
}

// 调用示例
console.log(filterID("4", data));

运行结果

[
    {id: 1, name: 'Gill'},
    {id: 2, name: 'Gill2'},
    {id: 3, name: 'Gill3'}
]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 07:07:15