Is there a way to return the missing values of list_a from list_b in TypeScrpit?
For example:
var a1 = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
var a2 = ['a', 'b', 'c', 'd', 'z'];
The result value is
['e', 'f', 'g'].
thanks in advance
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"]
Edit
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
.
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"]
Typescript only provides design / compile time help, it doesn't add JavaScript features. So the solution that works in JavaScript will work in Typescript.
Plenty of ways to solve this, my goto choice would be lodash: https://lodash.com/docs#difference
_.difference(['a', 'b', 'c', 'd', 'e', 'f', 'g'],['a', 'b', 'c', 'd']);
来源:https://stackoverflow.com/questions/38498258/typescript-difference-between-two-arrays