Javascript function to group repeated values of an array with totals

This post was published in 2011 and is kept here for reference. It may contain information that's outdated or inaccurate. All external links and references have been updated to point to archived versions on archive.org where possible.

Something that took a little while to pull of well while working on the JS challenge this week, thought I’d throw it up here as it has its uses practically for grouping like array values with totals:

var testdata = ['a','a','a','b','b','c','c','c','c','d','d','d','e'];
var i=0, x, count, item;
while(i < testdata.length){
    count = 1;
    item = testdata[i];
    x = i+1;

    while(x < testdata.length && (x=testdata.indexOf(item,x))!=-1){
        count+=1;
        testdata.splice(x,1);
    }
    testdata[i] = new Array(testdata[i],count);
    ++i;
}
console.log(testdata);

This is outputting to the console log for the sake of testing it, but the kind of output you’d expect to see is a multidimensional array.

Should have the rest of my solution to the challenge up tomorrow, with a nice post explaining the tough time Tomas and I have had fighting our urge to reveal code/brainstorm together.

This post is also available in plain text

[Comments]

Want to comment? You can do so via Github.
Comments via Github are currently closed.

[Webmentions]

Want to reply? I've hooked up Webmentions, so give it a go!