A Practical Example

Let’s say that you are 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.

JavaScript does not come with such a function built in, so we’ll have to create our own. Here’s one possible implementation:

 function​ intersection(first_array, second_array){
 var​ result = [];
 
 for​ (​var​ i = 0; i < first_array.length; i++) {
 for​ (​var​ j = 0; j < second_array.length; j++) {
 if​ (first_array[i] ...

Get A Common-Sense Guide to Data Structures and Algorithms now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.