Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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']. 
like image 900
Galma88 Avatar asked Jul 21 '16 07:07

Galma88


People also ask

Can we compare two arrays in JavaScript?

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.

How can you tell if two arrays of objects are equal in TypeScript?

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 !==

Can two arrays be compared?

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).


2 Answers

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)

like image 82
Nitzan Tomer Avatar answered Oct 03 '22 01:10

Nitzan Tomer


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']); 
like image 33
Ross Scott Avatar answered Oct 03 '22 01:10

Ross Scott