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

JavaScript对象数组过滤:移除包含指定产品码的元素

Fixing the Array Filter Issue

Hey there! Let's sort out this filtering problem you're working on.

First, let's break down what's wrong with your current code:

response.filter(obj => {return obj.product == elProd.includes(obj.product)})

The issue here is two-fold:

  1. elProd.includes(obj.product) returns a boolean (true or false), but you're comparing it to obj.product (a string like "EL" or "AC"). These will never match, so your filter ends up returning unexpected results.
  2. You want to exclude objects where product exists in elProd, but your current logic doesn't handle this exclusion properly.

The Correct Solution

We need to check if obj.product is not present in elProd, and return that boolean result directly in the filter callback:

const response = [ { id: 1, product: 'EL' }, { id: 2, product: 'AC' }, { id: 3, product: 'AC' }, { id: 4, product: 'AD' }, { id: 5, product: 'DE' }, ];
const elProd = ["EL", "DE"];

const filteredResponse = response.filter(obj => !elProd.includes(obj.product));

console.log(filteredResponse);
// Output: [ { id: 2, product: 'AC' }, { id: 3, product: 'AC' }, { id: 4, product: 'AD' } ]

Optional Performance Optimization

If elProd is large (like hundreds or thousands of items), Array.includes() can be slow since it checks every element each time. A better approach is to convert elProd to a Set first—Set.has() is an O(1) operation, making the filter much faster for bigger datasets:

const elProdSet = new Set(elProd);
const filteredResponse = response.filter(obj => !elProdSet.has(obj.product));

This works exactly the same as the basic solution, but with improved performance for large collections.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 17:42:59