August 2024
Intermediate to advanced
516 pages
11h 47m
English
Suppose you’re writing a JavaScript application, and somewhere in your code you find that you need to get the intersection between two arrays. The intersection is a list of all the values that occur in both of the arrays. For example, if you have the arrays [3, 1, 4, 2] and [4, 5, 3, 6], the intersection would be a third array [3, 4] since both of those values are common to the two arrays.
Here’s one possible implementation:
| | function intersection(firstArray, secondArray) { |
| | const result = []; |
| | |
| | for (const i of firstArray) { |
| | for (const j of secondArray) { |
| | if (i === j) { |
| | result.push(i); |
| | } |
| | } |
| | } |
| | |
| | return result; |
| | } |
Here, we’re running nested loops. In the outer loop, we iterate over each value ...
Read now
Unlock full access