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

JavaScript中从对象数组内数组删除指定值并返回新数组的最优方案

问题描述

我试过用findIndex、map、Object.entries这些方法,想找最优解。需求很明确:

  • 从customerNumber数组[1,2,3,4,5]里移除2;
  • 把customerNumber的值改成[1,3,4,5];
  • 更新到filterState数组里。

下面是初始数据、我写的函数代码、调用方式,还有期望的输出:

初始数据

let filterState = [
    {'customerNumber': [1,2,3,4,5]},
    {'ward': [10, 20, 30, 40, 50]},
    {'enrolledDate': [111, 222,333, 444,555]},
    {'district': ['AAA', 'BBB','CCCC', 'DDD']},
    {'onBoardingSmsStatus': false}
]

当前实现的函数

function removedChip(type='', value=0, filterState=[]) {

for(let i=0; i<filterState.length; i++) {


    let entries = Object.keys(filterState)
    .forEach(function eachKey(key) { 
        console.log(key); // 打印key
        console.log(filterState[key]); // 打印value
    });
    console.log(entries)
    let searchIndex = entries.findIndex(type);

    console.log('searchIndex', searchIndex)
    console.log('type of ', filterState[searchIndex])
    for(let i=0; i<filterState[searchIndex]; i++) {
        // 从customerNumber数组[1,2,3,4,5]移除2
        // 设置customerNumber的值为数组[1,3,4,5]
        // 把更新后的customerNumber合并到filterState数组
    }
}
}

函数调用方式

removedChip('customerNumber', 10, filterState)

期望输出

let filterState = [
    {'customerNumber': [1,3,4,5]},
    {'ward': [10, 20, 30, 40, 50]},
    {'enrolledDate': [111, 222,333, 444,555]},
    {'district': ['AAA', 'BBB','CCCC', 'DDD']},
    {'onBoardingSmsStatus': false}
]
最优解决方案

直接上高效简洁的实现:

function removedChip(type, value, filterState) {
    // 定位到包含目标key的对象
    const targetItem = filterState.find(item => Object.hasOwn(item, type));
    if (targetItem) {
        // 过滤掉指定值,更新数组
        targetItem[type] = targetItem[type].filter(item => item !== value);
    }
}

// 注意:调用时要传对要移除的value,你之前传的10应该改成2
removedChip('customerNumber', 2, filterState);

原函数的问题点

  1. forEach没有返回值,entries会是undefined,调用entries.findIndex直接报错;
  2. 嵌套循环完全没必要,而且内层循环的条件i < filterState[searchIndex]逻辑错误,filterState[searchIndex]是对象,不是数字;
  3. 函数调用时传错了value参数,应该传要移除的2而不是10。

为什么这个方案最优?

  • 用find直接定位目标对象,时间复杂度O(n),比手动循环简洁高效;
  • filter一行代码完成数组元素移除,可读性拉满;
  • 只修改需要更新的部分,不干扰其他元素,逻辑清晰。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 00:36:27