'Typescript difference between two arrays
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'].
Solution 1:[1]
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"]
Solution 2:[2]
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']);
Solution 3:[3]
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', '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"] */
Solution 4:[4]
You can look for both values:
const removed = before.filter((x: any) => !after.includes(x));
const added = after.filter((x: any) => !before.includes(x));
Solution 5:[5]
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);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Ross Scott |
| Solution 3 | |
| Solution 4 | Jonathan |
| Solution 5 | Sonu |
