Categories
TypeScript Answers

How to get the difference between two arrays with TypeScript?

Spread the love

Sometimes, we want to get the difference between two arrays with TypeScript.

In this article, we’ll look at how to get the difference between two arrays with TypeScript.

How to get the difference between two arrays with TypeScript?

To get the difference between two arrays with TypeScript, we use the array filter and indexOf methods.

For instance, we write

const a1 = ["a", "b", "c", "d", "e", "f", "g"];
const a2 = ["a", "b", "c", "d", "z"];

const missing = a1.filter((item) => a2.indexOf(item) < 0);
console.log(missing);

to get the items in a1 that aren’t in a2 and return the list of items as an array.

To do this, we call a1.filter with a callback that checks if each item in a1 isn’t in a2 with a2.indexOf(item) < 0.

Then missing would have the items in a1 that aren’t in a2 in an array.

Conclusion

To get the difference between two arrays with TypeScript, we use the array filter and indexOf methods.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.