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(" ") +
" " + currentValue.slice(2).join(" ") + "");
}
print(arrVal.reduce(group, []).reduce(format, []).join(" "));
Leave a Reply