两个数组之间的打字稿差异 [英] Typescript difference between two arrays

查看:32
本文介绍了两个数组之间的打字稿差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法从TypeScrpit中的list_b返回list_a的缺失值?

Is there a way to return the missing values of list_a from list_b in TypeScrpit?

例如:

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

结果值为

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

推荐答案

可能有很多方法,例如使用 Array.prototype.filter():

There are probably a lot of ways, for example using the 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 的元素,并将它(但在一个新数组中)减少到 a1 中的元素(因为我们正在迭代它的元素)并且在 a2 中缺失.

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.

a2 中在 a1 中缺失的元素将不会包含在结果数组中 (missing),因为过滤器函数没有't 迭代 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:

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

(代码在操场上)

这篇关于两个数组之间的打字稿差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆