
I was asked an interesting question a couple of days ago. The question was as follows:
If you have two arrays of say, numbers, and you wanted to list only the numbers that exist in both. How would you go about doing this in JavaScript?
The answer was not immediately evident but, I had a basic idea of how one might go about this so, I jumped in and started coding. jQuery has a very useful utility function called inArray that, as expected, allows you to test whether a specific element exists in an array. I did not want to include the entire jQuery library literally for just one function so, I decided to have a look at the jQuery source and the implementation code for the inArray function. Below is the function:
inArray: function( elem, array ) {
if ( indexOf ) {
return indexOf.call( array, elem );
}
for ( var i = 0, length = array.length; i < length; i++ ) {
if ( array[ i ] === elem ) {
return i;
}
}
return -1;
}
The indexOf variable used in the first if statement get’s assigned the value, which will be a function, of Array.prototype.indexOf earlier on in the jQuery source. indexOf is a new function that has been added to the Array object in ECMAScript 5 and implemented in JavaScript 1.6. It will either return the index at which it found the item in the array or, -1 if the item was not found.
Browser support for this function is very good but, Internet Explorer 8 and below does not offer support for this hence the fallback for loop if the if condition fails. With this piece of the puzzle in place, we can proceed to write the matching function:
var arrayMatcher = function(firstArray, secondArray) {
var results = [],
arrayLength = firstArray.length;
for(i = 0; i < arrayLength; i++) {
if(inArray(firstArray[i], secondArray) > -1) {
results.push(firstArray[i]);
}
}
return results;
};
Pretty darn simple, let’s step through the code. The arrayMatcher function first of all takes two arrays as parameters, note that the arrays does not have to be of equal length, just ensure that you pass it the longer of the two as the first parameter. Next we create two variables, the results array that will contain the matched items as well as storing the length of the first array in the arrayLength variable.
Storing the length of the array and then using the resulting variable in your for loops is a general best practice to optimize performance, however small an optimization it might be. Reason for this is that the length of the array does not have to be calculated every time we go through the loop.
Inside our for loop we test if the current item in the first array exists in the second using the inArray function. If it does, we go ahead and push it onto the results array. Once our loop completes, we simply return the result to the calling function. And that, in a nutshell, is that. I hope you find this little utility useful. You can grab the code from my Utils repository on Github.
Image courtesy: Comrade_S
