How to efficiently compare two integer arrays and find the items in both arrays with JavaScript?

Sometimes, we want to efficiently compare two integer arrays and find the items in both arrays with JavaScript.

In this article, we’ll look at how to efficiently compare two integer arrays and find the items in both arrays with JavaScript.

How to efficiently compare two integer arrays and find the items in both arrays with JavaScript?

To efficiently compare two integer arrays and find the items in both arrays with JavaScript, we can use some JavaScript array methods.

For instance, we write:

const a1 = [15, 551, 25, 910, 11]
const a2 = [25, 11, 785, 880, 15]
const inBoth = a1.filter(a => a2.includes(a))
console.log(inBoth)

to call a1.filter with a callback that checks if a1 array entry a is in a2 with a2.includes.

Therefore, inBoth is [15, 25, 11].

Conclusion

To efficiently compare two integer arrays and find the items in both arrays with JavaScript, we can use some JavaScript array methods.