两个数组之间的Typescript差异

r6hnlfcb  于 2023-05-30  发布在  TypeScript
关注(0)|答案(6)|浏览(299)

有没有一种方法可以从TypeScrpit中的list_B返回list_a的缺失值?
例如:

var a1 = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
var a2 = ['a', 'b', 'c', 'd', 'z'];

结果值为

['e', 'f', 'g'].
ryoqjall

ryoqjall1#

可能有很多方法,例如使用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在操场上)

编辑

filter函数运行a1的元素,并将其减少(但在新数组中)为a1中的元素(因为我们正在迭代它的元素),并且在a2中缺失。
a1中缺少的a2中的元素不会包含在结果数组(missing)中,因为filter函数不会迭代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在操场上)

b4lqfgs4

b4lqfgs42#

Typescript只提供设计/编译时帮助,它不添加JavaScript特性。因此,在JavaScript中工作的解决方案将在Typescript中工作。
有很多方法可以解决这个问题,我的后藤选择是lodash:https://lodash.com/docs#difference

_.difference(['a', 'b', 'c', 'd', 'e', 'f', 'g'],['a', 'b', 'c', 'd']);
njthzxwz

njthzxwz3#

你只能使用这种方法。先坐大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"] */
mcvgt66p

mcvgt66p4#

您可以查看这两个值:

const removed = before.filter((x: any) => !after.includes(x));
const added = after.filter((x: any) => !before.includes(x));
uz75evzq

uz75evzq5#

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

i7uaboj46#

为什么不利用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"]

相关问题