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(" ") + 
			" " + currentValue.slice(2).join(" ") + "");
}

print(arrVal.reduce(group, []).reduce(format, []).join(" "));

Posted

in

by

Comments

2 responses to “JavaScript reduce”

  1. Matt Ryall Avatar

    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.

  2. […] – 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

Your email address will not be published. Required fields are marked *