17

I'm using Underscore's template() method in BackboneJS views. I'd like to show a list of alphabet letters in my view in order to sort a collection by letter.

As a result, I have a list of 26 links (one link = one letter) in my view. Instead of copy-pasting each link (which is very bad for code maintainability), I was wondering if it was possible to loop through the alphabet via underscoreJS.

Result to display :

<li ><a href="#">a</a></li>
<li ><a href="#">b</a></li>
<li ><a href="#">c</a></li>
...
<li ><a href="#">z</a></li>

9 Answers 9

47
var alphabet = "abcdefghijklmnopqrstuvwxyz".split("");
_.each(alphabet, function(letter) {
  console.log(letter);
});

That's how you could do it.

14
  1. Create a range with the charcodes

    var alphas = _.range(
        'a'.charCodeAt(0),
        'z'.charCodeAt(0)+1
    ); 
    // [97 .. 122]
    
  2. Create an array with the letters

    var letters = _.map(alphas, a => String.fromCharCode(a));
    // see @deefour comment
    
    // Non ES6 version
    // var letters = _.map(alphas, function(a) {
    //    return String.fromCharCode(a);
    // });
    
    // [a .. z]
    
  3. Inject into your template

    var tpl = 
    '<ul>'+
        '<% _.each(letters, function(letter) { %>'+
            '<li><%= letter %></li>'+
        '<% }); %>'+
    '</ul>';
    var compiled = _.template(tpl);
    var html = compiled({letters : letters});
    

And a demo http://jsfiddle.net/hPdSQ/17/

var alphas = _.range(
    'a'.charCodeAt(0),
    'z'.charCodeAt(0)+1
); 

var letters = _.map(alphas, a => String.fromCharCode(a));

var tpl = 
'<ul>'+
    '<% _.each(letters, function(letter) { %>'+
        '<li><%= letter %></li>'+
    '<% }); %>'+
'</ul>';
var compiled = _.template(tpl);

var html = compiled({letters : letters});

document.getElementById('res').innerHTML = html;
<script src="http://underscorejs.org/underscore-min.js"></script>
<div id='res'></div>

1
  • 2
    Be aware, the map over alphas in this answer does not return an array of raw characters, "a", "b", "c", .... You'll instead get unicode strings like "a\u0001\u0000", "b\u0001\u0000", "c\u0001\u0000", .... You should instead use an arrow function like a => String.fromCharCode(a) to only pass the first argument (fromCharCode accepts an arbitrary number of arguments, causing whatever else lodash passes to the map callback to be converted to null values shown above).
    – deefour
    Aug 14, 2016 at 17:27
7
for(var letter=65;letter<91;letter++)
{
var _char = String.fromCharCode(letter);
console.log(_char);
}

or use from 97 - 123 ascii code for lowercase letters

1
  • Really its simple! declare an array and push each _char to that, ur array with alphabets ready! Jun 10, 2020 at 14:43
4

for (var i = 'a'.charCodeAt(0); i <= 'z'.charCodeAt(0); i++) {
  console.log(String.fromCharCode(i));
}

2
  • 1
    What is the use of charCodeAt(0) concatted to your starting and ending indexes? May 4, 2018 at 18:01
  • Okay, yeah, relooking now, this does look right; it might be slightly slower than Medo Medo's, but it is slightly more readable. Jun 29, 2018 at 13:26
3

Using ES6 for-of:

for(let char of "abcdefghijklmnopqrstuvwxyz" )
  console.log(char); // prints 'a' to 'z'
   

Pretty easy to use that in a template, and you could use Babel to transpile it to code for browsers which lack support for that syntax.

1
  • 1
    You didn't answer the question directly about backbone or underscore but helped me nonetheless since I'm in ES6+. Thanks.
    – staylorx
    Dec 13, 2016 at 23:56
1

Another approach with underscore (or loadash):

_.map(_.range(26), function(i) { return String.fromCharCode(97 + i) });

// returns ['a', 'b', ..., 'z']
0

Using underscore.js and jQuery in conjunction will help you acheive this (underscore.js is incapable of doing DOM insertion/manipulation by itself).

var abc = ['a', 'b', 'c', 'd']; //i disregarded how you get the list of letters.

_.each(abc, function(letter){
    $('ul').append('<li><a href="#">'+letter+'</a></li>');
});

Also made a fiddle for you

0

Underscore don't have such ability, but your case could do some trick on the template. change your template like this:

<% for(var i=65; i<90; i++) { %>
<li ><a href="#"><% print(String.fromCharCode(i)); %></a></li>
<% } %>

this should be what you want.

1
  • you missed Z , var i = 65; i <= 90; i++ , it needed <= , but close enough :)
    – med116
    Sep 10, 2014 at 20:38
0

Here's an improved* version of @Medo Medo's pure JS code:

    var letters=[], letter_first = 'a', letter_last = 'z' // you can also use A and Z
    for (var letter=letter_first.charCodeAt(0);letter<=letter_last.charCodeAt(0);letter++)
      letters.push(String.fromCharCode(letter))
    document.write(letters.join(''))

  • Fixed the "var" declaration
  • Added direct letter detection
  • Collected the result into an array in order to have only one output
  • Made the code runnable right here
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.