Typescript difference between two arrays Typescript difference between two arrays arrays arrays

Typescript difference between two arrays


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

(code in playground)


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

(code in playground)


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


You can only use this method. With the larger table first.

const a1 = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];const a2 = ['a', 'b', 'c', 'd', 'z'];const difference = a1.filter(x => !a2.includes(x));console.log(difference);