两个数组之间的打字稿差异 [英] Typescript difference between two arrays
本文介绍了两个数组之间的打字稿差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有办法在TypeScrpit中从list_b返回list_a的缺失值?
Is there a way to return the missing values of list_a from list_b in TypeScrpit?
例如:
var a1 = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
var a2 = ['a', 'b', 'c', 'd', 'z'];
结果值为
['e', 'f', 'g'].
预先感谢
推荐答案
There are probably a lot of ways, for example using the Array.prototype.filter():
var a1 = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
var a2 = ['a', 'b', 'c', 'd'];
let missing = a1.filter(item => a2.indexOf(item) < 0);
console.log(missing); // ["e", "f", "g"]
( filter
函数在a1
的元素上运行,并将其缩小(但在新数组中)为a1
中的元素(因为我们正在对其元素进行迭代)而在a2
.
The filter
function runs over the elements of a1
and it reduce it (but in a new array) to elements who are in a1
(because we're iterating over it's elements) and are missing in a2
.
元素不会包含在结果数组(missing
)中,因为过滤器函数不会遍历a2
元素:
Elements in a2
which are missing in a1
won't be included in the result array (missing
) as the filter function doesn't iterate over the a2
elements:
var a1 = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
var a2 = ['a', 'b', 'c', 'd', 'z', 'hey', 'there'];
let missing = a1.filter(item => a2.indexOf(item) < 0);
console.log(missing); // still ["e", "f", "g"]
( 查看全文