[英]Count number of overlapping items in two arrays
I have two arrays, of which the Remove
should be removed from the List
, and the number removed should be counted. 我有两个数组,其中应该从
List
Remove
,并且应该计算删除的数量。
I'm using this to remove those from 'Remove'
: 我正在使用它从
'Remove'
删除它们:
let output=this.List.filter((el)=>{
return this.Remove.indexOf(el) <0;
})
This is working fine, but I'd like to count the number of items that have overlapped, and thus been removed in the filter. 这项工作正常,但我想计算重叠的项目数,因此已在过滤器中将其删除。
For example, if List=['1','2','3','4','5']
and Remove=['1','4']
, count
would be 2
. 例如,如果
List=['1','2','3','4','5']
和Remove=['1','4']
,则count
为2
。
Many thanks! 非常感谢!
You can do this in one reduce
run. 您可以一次
reduce
运行。 For example, you can create an object and track both cleared array and a number of deleted elements: 例如,您可以创建一个对象并跟踪清除的数组和多个已删除的元素:
const a = [1,2,3,4,5,6,7]; const b = [1,4,9]; // elements to remove const c = a.reduce((acc, cur) => b.includes(cur) ? Object.assign(acc, {n: acc.n + 1}) : Object.assign(acc, {res: acc.res.concat(cur)}), { n: 0, res: []}); console.log(c)
If you don't want to compare lengths as suggested in comments (which is fine...), I can propose you the following solution using a counter: 如果您不想按照注释中的建议比较长度(很好...),我可以使用计数器为您提供以下解决方案:
let list = ['1', '2', '3', '4', '5'], remove = ['1', '4'], overlap = 0; let output = list.filter(el => { let bool = remove.indexOf(el) < 0; if (!bool) overlap++; return bool; }); console.log(overlap);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.