如何在JavaScript中根据另一数组的所有条件过滤数组?
数组过滤实现方案
需求说明
我有两个数组,需要过滤arrayFirst,只保留满足arraySecond中所有字段条件的元素。
原始数组
arrayFirst
const arrayFirst = [ {id: 417, tseAccountId: 21997, isin: 'IRO3ASKZ0001', totalBuyQuantity: 300000, totalSellQuantity: 2000}, {id: 418, tseAccountId: 21997, isin: 'IRO7MFMP0001', totalBuyQuantity: 300000, totalSellQuantity: 2000}, {id: 419, tseAccountId: 21997, isin: 'IRT1CSNF0001', totalBuyQuantity: 1000, totalSellQuantity: 0}, {id: 420, tseAccountId: 21997, isin: 'IRO1BSDR0001', totalBuyQuantity: 1000, totalSellQuantity: 0}, {id: 423, tseAccountId: 21997, isin: 'IRO1BMLT0001', totalBuyQuantity: 300000, totalSellQuantity: 0} ];
arraySecond
const arraySecond = [ {title: 'totalBuyQuantity', value: 300000}, {title: 'totalSellQuantity', value: 20000}, {title: 'isin', value: 'IRO3ASKZ0001'} ];
实现思路
- 将
arraySecond转换为键值对对象,简化后续条件匹配逻辑; - 用
arrayFirst的filter方法遍历元素,校验每个元素是否符合所有过滤条件。
代码实现
// 转换arraySecond为键值对对象 const filterMap = arraySecond.reduce((acc, cur) => { acc[cur.title] = cur.value; return acc; }, {}); // 执行过滤 const result = arrayFirst.filter(item => { return Object.keys(filterMap).every(key => item[key] === filterMap[key]); }); console.log(result);
注意事项
你给出的预期结果中,元素的totalSellQuantity值为2000,但arraySecond中对应的条件值是20000,二者不匹配,实际运行上述代码会得到空数组。如果是笔误,将arraySecond里的totalSellQuantity值改为2000,就能得到你预期的结果:
[{id: 417, tseAccountId: 21997, isin: 'IRO3ASKZ0001', totalBuyQuantity: 300000, totalSellQuantity: 2000}]
内容的提问来源于stack exchange,提问作者zahra zamani
相关产品推荐
相关产品推荐

