JavaScript reduce
Tonight Matt posted a JavaScript solution to a problem he saw described elsewhere. Here’s a version that I whipped up to use JavaScript 1.8′s new Array.prototype.reduce function.
var arrVal = ["a", "b", "c", "c", "d", "e", "e", "e", "e", "e", "f", "e", "f", "e", "f", "a", "a", "a", "f", "f", "f"]; function group(previousValue, currentValue, index, arr) { if (index > 0 && arr[index - 1] == currentValue) return previousValue.slice(0,-1).concat([previousValue.slice(-1)[0].concat(currentValue)]); return previousValue.concat([[currentValue]]); } function format(previousValue, currentValue, index, arr) { return previousValue.concat( currentValue.length < 3 ? currentValue.join(" ") : currentValue.slice(0,2).join(" ") + " <span>" + currentValue.slice(2).join(" ") + "<span>"); } print(arrVal.reduce(group, []).reduce(format, []).join(" "));


Wow, that is cool. Using all four arguments of the reduce function is impressive.
Rather than using reduce, you could make group() recursive and pass the output array to it. This might make the array manipulation a bit easier because you don’t have to return it:
Not very functional, perhaps.
It took me a while to understand why you’re putting double brackets around this:
The overloaded argument handling of Array.concat is quite annoying in this case.