typescript 两个数组之间的打字稿差异
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38498258/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Typescript difference between two arrays
提问by Galma88
Is there a way to return the missing values of list_a from list_b in TypeScrpit?
有没有办法从 TypeScrpit 中的 list_b 返回 list_a 的缺失值?
For example:
例如:
var a1 = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
var a2 = ['a', 'b', 'c', 'd', 'z'];
The result value is
结果值为
['e', 'f', 'g'].
thanks in advance
提前致谢
回答by Nitzan Tomer
There are probably a lot of ways, for example using the Array.prototype.filter():
可能有很多方法,例如使用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"]
(操场上的代码)
Edit
编辑
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
.
该filter
函数运行在 的元素上a1
并将其(但在一个新数组中)减少到a1
在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:
a2
缺少的元素a1
不会包含在结果数组 ( missing
) 中,因为过滤器函数不会遍历a2
元素:
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"]
(操场上的代码)
回答by Ross Scott
Typescript only provides design / compile time help, it doesn't add JavaScript features. So the solution that works in JavaScript will work in Typescript.
Typescript 仅提供设计/编译时帮助,不添加 JavaScript 功能。所以适用于 JavaScript 的解决方案也适用于 Typescript。
Plenty of ways to solve this, my goto choice would be lodash: https://lodash.com/docs#difference
有很多方法可以解决这个问题,我的 goto 选择是 lodash:https://lodash.com/docs#difference
_.difference(['a', 'b', 'c', 'd', 'e', 'f', 'g'],['a', 'b', 'c', 'd']);