Tip: getting values from an options list

So, if you’ve ever converted an options list into a single array of values you might have intuitively done this:

var select = $('#mySelectElement')[0];
var values = new Array();
for (var i=0; i < select.length; i++) {

Pretty boring aye?

There is a snazzier (is that a word?) alternative, which is to use jQuery.map:

var select = $('#mySelectElement')[0];
var values = $.map(select.options, function(n) { 
    return n.value; 

OK, only one line saving but doesn’t that feel good?!?


  1. dalin at

    If this was PHP I would say "bad idea". But I know much less about JavaScript so perhaps it's not.

    in option 1 you use language constructs (I would think it would be even better to use values[] rather than the method .push). In option 2 you use a method to run a callback function on each element. I'm guessing there's an order of magnitude difference in performance (if not more). Albeit with a select box there's probably not too many options to iterate through, but other scenarios may have significantly more.

  2. caphun at

    @dalin: Yes, definitely. Using values[] would be quicker than push but in most cases you won't notice. If I were wearing my optimization hat I'd also use <code>document.getElementById('mySelectElement')</code> to add to that.

    jQuery.map at its heart is a for loop with a callback. That's all it is. I see option one as a common pattern we run into often and option 2 as a possible solution to that pattern.

  3. Less code means less bandwidth and more efficiency in usage of cache for high traffic website (less hacking risk, less risk in DDOS attack, etc). Let's client's computers do the rest (that's the philosophy of Client-Side Javascript). So, as a software engineer from a B2B firm, I prefer one line version:

    var values=$.map($('#mySelectElement')[0].options, function(n){return n.value});