有没有办法在TypeScript中返回list_a中与list_b不匹配的值?
例如:
var a1 = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
var a2 = ['a', 'b', 'c', 'd', 'z'];
结果值为
['e', 'f', 'g'].
有没有办法在TypeScript中返回list_a中与list_b不匹配的值?
例如:
var a1 = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
var a2 = ['a', 'b', 'c', 'd', 'z'];
结果值为
['e', 'f', 'g'].
可能有很多方法,例如使用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
数组,并将其中满足条件的元素(不在 a2
数组中)添加到结果数组 missing
中,原数组 a1
不会被修改。
a2
数组中不存在于 a1
数组中的元素不会被加入结果数组 (missing
),因为 filter 函数只遍历 a1
数组中的元素,而不会遍历 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"]
["e", "f", "g"]
,就像你想要的一样... 所以我不确定你的意思是什么。 - Nitzan Tomera2
中添加了z
,我的脚本仍将返回["e", "f", "g"]
。即使是var a2 = ['a', 'b', 'c', 'd', 'z', 'hey', 'there'];
,它仍将返回所请求的缺失值,请在此处检查。let missing = a1.filter(item => a2.indexOf(item) < 0); console.log(missing); // ["e", "f", "g"] - Nitzan TomerTypescript仅提供设计/编译时的帮助,不会添加JavaScript功能。因此在JavaScript中可行的解决方案也适用于Typescript。
有很多解决方法,我的首选是lodash:https://lodash.com/docs#difference
_.difference(['a', 'b', 'c', 'd', 'e', 'f', 'g'],['a', 'b', 'c', 'd']);
您只能使用此方法。首先使用较大的表格。
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);
/* ["e","f","g"] */
console.log(difference_a2);
/* ["x","y","z"] */
您可以查找两个值:
const removed = before.filter((x: any) => !after.includes(x));
const added = after.filter((x: any) => !before.includes(x));
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);
为什么不利用JavaScript的强大功能呢 :-)
var a1 = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
var a2 = ['a', 'b', 'c', 'd', 'k', 'l', 'M', 'j'];
let difference: string[] = [];
difference = difference.concat(a1.filter(item => a2.indexOf(item) < 0))
.concat(a2.filter(item => a1.indexOf(item) < 0));
or
difference = difference.concat(a1.filter(item => !a2.include(item)))
.concat(a2.filter(item => !a1.include(item)));
console.log(difference); // ["e", "f", "g", "k", "l", "M", "j"]