如何获得两个字符串数组的区别? [英] How to get the difference of two string arrays?
本文介绍了如何获得两个字符串数组的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想得到两个字符串数组之间的确切区别.
I want to get the exact difference between two string arrays.
const array1 = ['T','E','A','P','A','P','E','R'];
const array2 = ['T','A','P'];
预期的输出数组:
['E','A','P','E','R']
我尝试过这种方法:
const output = array1.filter(char => array2.includes(char));
但这会删除字符的所有实例,例如:
But that removes all instances of a character, like:
['E','E','R']
我是新手,所以您能指导我正确的方向吗?
I'm a newbie, so could you guide me to the right direction?
推荐答案
您可以关闭第二个数组的索引,并增加索引并将其从结果集中删除.
You could take a closure over the index for the second array and increment the index and remove this item from the result set.
var array1 = ['T', 'E', 'A', 'P', 'A', 'P', 'E', 'R'],
array2 = ['T', 'A', 'P'],
result = array1.filter((i => v => array2[i] !== v || !++i)(0));
console.log(result);
没有预定义顺序array2
的另一种方法.
A different approach without a predefined order of array2
.
var array1 = ['T', 'E', 'A', 'P', 'A', 'P', 'E', 'R'],
array2 = ['T', 'A', 'P'],
set2 = new Set(array2)
result = array1.filter(v => !set2.delete(v));
console.log(result);
这篇关于如何获得两个字符串数组的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文