两个数组之间的打字稿差异
Posted
技术标签:
【中文标题】两个数组之间的打字稿差异【英文标题】:Typescript difference between two arrays 【发布时间】:2016-11-24 16:38:44 【问题描述】:有没有办法从 TypeScript 中的 list_b 返回 list_a 的缺失值?
例如:
var a1 = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
var a2 = ['a', 'b', 'c', 'd', 'z'];
结果值为
['e', 'f', 'g'].
【问题讨论】:
所以您想比较 a1 和 a2 并检查 a2 中缺少哪个并打印它们或将它们添加到 a2 中?我不确定我是否理解正确.. 我需要 a2 中的 a1 中缺少的元素,但我不需要 a1 中的 a2 中缺少的元素。 【参考方案1】:可能有很多方法,例如使用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"]
(code in playground)
编辑
filter
函数遍历a1
的元素,并将其(但在一个新数组中)减少为a1
中的元素(因为我们正在迭代它的元素)并且在@ 中丢失987654329@。
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"]
(code in playground)
【讨论】:
看起来不错,但 ii 也显示了我在 B 中拥有而在 A 中没有的值。但我不需要它们。 它返回["e", "f", "g"]
就像你想要的那样......所以我不确定你的意思
我编辑了我的问题。如果我在 a2 中有一个“z”,你的脚本也会返回“z”,但我不需要它
不,即使将z
添加到a2
,我的脚本仍将返回["e", "f", "g"]
。即使var a2 = ['a', 'b', 'c', 'd', 'z', 'hey', 'there'];
它仍然会返回请求的缺失值check it here。
太完美了,谢谢。我刚刚为任何感兴趣的人编写了这个小的“数组差异”函数: const arrayDiffs = (oldArray: any[] = [], newArray: any[] = []) => const added = newArray.filter((item) = > oldArray.indexOf(item) newArray.indexOf(item)
【参考方案2】:
Typescript 仅提供设计/编译时帮助,不添加 javascript 功能。因此,适用于 JavaScript 的解决方案将适用于 Typescript。
有很多方法可以解决这个问题,我的 goto 选择是 lodash: https://lodash.com/docs#difference
_.difference(['a', 'b', 'c', 'd', 'e', 'f', 'g'],['a', 'b', 'c', 'd']);
【讨论】:
【参考方案3】:您只能使用此方法。首先是较大的表。
const a1 = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
const a2 = ['a', 'b', 'c', 'd', 'x', 'y', 'z'];
const difference_a1 = a1.filter(x => !a2.includes(x));
const difference_a2 = a2.filter(x => !a1.includes(x));
console.log(difference_a1);
console.log(difference_a2);
【讨论】:
【参考方案4】:您可以同时查找这两个值:
const removed = before.filter((x: any) => !after.includes(x));
const added = after.filter((x: any) => !before.includes(x));
【讨论】:
【参考方案5】:const a1 = ['a', 'b', 'c', 'd', 'e', 'f'];
const a2 = ['a', 'b', 'c'];
let bigArray = null;
let smallArray = null;
if(a1.length >= a2.length)
bigArray = a1;
smallArray =a2;
else
bigArray= a2;
smallArray =a1;
const diff = bigArray.filter(item => smallArray.indexOf(item) < 0);
console.log(diff);
【讨论】:
以上是关于两个数组之间的打字稿差异的主要内容,如果未能解决你的问题,请参考以下文章