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:
elProd.includes(obj.product)returns a boolean (trueorfalse), but you're comparing it toobj.product(a string like "EL" or "AC"). These will never match, so your filter ends up returning unexpected results.- You want to exclude objects where
productexists inelProd, 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
相关产品推荐
相关产品推荐

