两个数组之间的打字稿差异

Typescript difference between two arrays

有没有办法在 TypeScrpit 中 return 来自 list_b 的 list_a 的缺失值?

例如:

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"]

(code in playground)


编辑

filter 函数遍历 a1 的元素并将其(但在新数组中)缩减为 a1 中的元素(因为我们正在迭代它是元素)并且在 a2 中缺失。

a2a1 中缺失的元素将不会包含在结果数组 (missing) 中,因为过滤函数不会迭代 [=15] =] 元素:

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)

Typescript 仅提供设计/编译时帮助,不添加 JavaScript 功能。因此,在 JavaScript 中有效的解决方案将在 Typescript 中有效。

有很多方法可以解决这个问题,我的 goto 选择是 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'];
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);

您只能使用此方法。首先是较大的table。

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));