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(" "));
  1. Matt Ryall says:

    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:

    previousValue[-1] = previousValue[-1].concat(currentValue);

    Not very functional, perhaps. :)

    It took me a while to understand why you’re putting double brackets around this:

    return previousValue.concat([[currentValue]]);

    The overloaded argument handling of Array.concat is quite annoying in this case.

  1. [...] – bookmarked by 4 members originally found by marthitacisneros on 2008-07-20 JavaScript reduce http://christopherowen.id.au/blog/2008/07/08/javascript-reduce/ – bookmarked by 3 members [...]

Leave a Reply