O'Reilly logo

A Common-Sense Guide to Data Structures and Algorithms by Jay Wengrow

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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] ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required