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'].
While JavaScript does not have an inbuilt method to directly compare two arrays, it does have inbuilt methods to compare two strings. Strings can also be compared using the equality operator. Therefore, we can convert the arrays to strings, using the Array join() method, and then check if the strings are equal.
var isEqual = function (value, other) { // Get the value type var type = Object. prototype. toString. call(value); // If the two objects are not the same type, return false if (type !==
Java provides a direct method Arrays. equals() to compare two arrays. Actually, there is a list of equals() methods in the Arrays class for different primitive types (int, char, ..etc) and one for Object type (which is the base of all classes in Java).
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)
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']);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With