Brain teaser

In response to Dustin Diaz (you’ll need a JavaScript 1.8 capable browser, or Ojay):

var arr = ['a', 'b', 'c', 'c', 'd','e', 'e',
'e', 'e', 'e', 'f', 'e', 'f', 'e',
'f', 'a', 'a', 'a', 'f', 'f', 'f'];

arr.reduce(function(memo, letter) {
    var last = memo[memo.length - 1];
    if (!last || last[0] != letter) memo.push([letter]);
    else last.push(letter);
    return memo;
}, []).map(function(group) {
    return group.join(' ').replace(/^(\w \w) (.*)$/g,
            '$1 <span>$2</span>');
}).join(' ');

// -> "a b c c d e e <span>e e e</span> \
//     f e f e f a a <span>a</span> f f \
//     <span>f</span>"

If you’ve enjoyed this article, you might enjoy my recently published book JavaScript Testing Recipes. It’s full of simple techniques for writing modular, maintainable JavaScript apps in the browser and on the server.