- #javaScript
- #arrays
- #snippets
Why find matching values in two arrays?
I have been recently coding my take on the classic Tetris game. In the process there were a few times I needed to check for matching element values in two different arrays. The results would then determine conditional statements such as go down, go left, go right, etcetara. So let us take a look.
Create the arrays
Of course in the game the arrays would be dynamic. Here we create two static arrays.
const firstNumbers = [33, 34, 35, 36]
const secondNumbers = [36, 37, 46, 47, 56, 57, 66, 67]
Combining methods
Sometimes we need to combine array methods to achieve success. My Array Methods in JavaScript page described the indexOf method returning the first index that matches a given condition. If there is no match the indexOf method returns -1. We can use this -1 as a conditional argument.
firstNumbers.indexOf(35) // returns 2
firstNumbers.indexOf(44) // returns -1
The filter method creates an array of elements that match a condition and all non-matching elements being filtered out. Therefore, if we filter out the indexOf results in the second array, we should achieve the aim.
const filtered = firstNumbers.filter((el) => secondNumbers.indexOf(el) !== -1)
// Array [ 36 ]
In this case we found a matching value of 36 in the two arrays! In the coding of Tetris, I then used the resulting array length as an if argument, like so:
if (filtered.length > 0) { doThis() }
Find non-matching values in two arrays?
If we can find the matching values in two arrays, we can also find non-matching values with a small tweak to the the code. Change !== -1 to === -1.
const filtered = firstNumbers.filter((el) => secondNumbers.indexOf(el) === -1)
// Array [ 33, 34, 35 ]
Tadaa.
For further reading on JavaScript array methods, please read my Array Methods in JavaScript article.
That’s it for now.
Thank you for stumbling across this website and for reading my blog post entitled Check for matching values in two arrays with JavaScript