SO Answer / Fast loop through Javascript array

See: http://stackoverflow.com/questions/11477314/fast-loop-through-javascript-array

by KooiInc MeHere

HTML

<h3>Fast filtering of a large array in a selectbox</h3>
<div id="result"></div>
<div id="noresult"></div>

CSS

body {margin:1em; font:normal 0.8em/1.6em verdana,arial;}

JavaScript

$('#result').html('Creating longlist...');
setTimeout(getList,1);

function createlist(){
    var container = $('#result'),selectinp;
       
    container.html('Created a list with 100.000 items, sorted and converted to option elements<br>'+
                   'Now try filtering the array, typing one or more numbers in the input box...<br>'+
                   '<br><select id="lstselect"></select> <input type="text" id="selectr"></input>');
    
    selectinp = $('#selectr');
    selectinp.on('keyup',function(){
      $('#noresult').html('');
      filter(this.value);
    });
    
    selectinp.on('keypress',function(e){
      if(!/[0-9]/i.test(String.fromCharCode(e.keyCode))){return false;}
      return true;
    });
    
    longlist = longlist.sort().map(function(item){return new Option(String(item),item);});
    selectinp.val('12');
    selectinp.focus();
    filter('12');
}

function getList(){
    var lst = [];
    for (var i=0;i<100001;i++){
      lst.push(Math.floor( (Math.random()*1000000)+10000 ));
    }
    longlist = lst;
    createlist();
    return lst;
}

function filter(term){
    if(!term || !term.length){
       $('#noresult').html('supply one or more numbers!');
       return true;
    }
    var re = RegExp('^'+term,'gi')
       ,maxToShow = 300
       ,selectBox = $('#lstselect')[0]
       ,optsfiltered = longlist.filter(function(item){
                        re.lastIndex = 0;
                        return re.test(item.value);
                      })
    ;
    if(!optsfiltered.length){
        $('#noresult').html('no items starting with ['+term+'] found');
        return true;
    }
    $('#noresult').html('filter: ['+term+'] =&gt; '+optsfiltered.length+' item(s)');
    optsfiltered = optsfiltered.slice(0,maxToShow);
    selectBox.options.length = 0;
    for (var i=0;i<optsfiltered.length;i++){
      selectBox[i] = optsfiltered[i];
    }
}