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'].
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'].
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"]
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"]
["e", "f", "g"] just like you wanted... So I'm not sure what you mean["e", "f", "g"] even with the added z to a2. even var a2 = ['a', 'b', 'c', 'd', 'z', 'hey', 'there']; it will still return the requested missing values, check it here.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', '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"] */
Why don't leverage the power of Javascript :-)
var a1 = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
var a2 = ['a', 'b', 'c', 'd', 'k', 'l', 'M', 'j'];
let difference: string[] = [];
difference = difference.concat(a1.filter(item => a2.indexOf(item) < 0))
.concat(a2.filter(item => a1.indexOf(item) < 0));
or
difference = difference.concat(a1.filter(item => !a2.include(item)))
.concat(a2.filter(item => !a1.include(item)));
console.log(difference); // ["e", "f", "g", "k", "l", "M", "j"]
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);