VLOOKUP For JavaScript

A user on StackOverflow wanted to know if VLOOKUP for Excel existed in JavaScript. Short answer is: no. However, it can be mimicked quite easily using the following:

Array.prototype.vlookup = function(needle,index,exactmatch){
  1.     index = index || 0;
  2.     exactmatch = exactmatch || false;
  3.     for (var i = 0; i < this.length; i++){
  4.         var row = this[i];
  5.  
  6.         if ((exactmatch && row[0]===needle) || row[0].toLowerCase().indexOf(needle.toLowerCase()) != -1)
  7.             return (index < row.length ? row[index] : row[0]);
  8.     }
  9.     return null;
  10. }

Short, but sweet. Basically, call this method off any (double) array variable and it will simulate the VLOOKUP of Excel. If no entry is found, it will return null. If the index specified exceeds that row’s element length, the first element is returned.

Flattr this!