Javascript function to group repeated values of an array with totals
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.
Related posts
- Android Auto on my HR-V's Android 4.0.4 head unit
I recently bought a 2018 Honda HR-V as our family car. It has a 7” touchscreen running Android 4.0.4, a version so old it predates Android Auto by about three years. It runs Android Auto now anyway, thanks to a small app I built over the course of a week.
- Rebuilding and analysing 4 years of Wordle stats from WhatsApp chat logs
Yes, I’m still playing Wordle in 2026. According to Wordle, I’ve played 1,559 games, I win 99% of the time, my current streak is 107 days and my longest is 278. Four numbers, and they’re mostly correct. What I don’t get is anything behind them. No per-game history. No way to compare a Tuesday to a Sunday. No sense of whether I’ve actually got better at this over four years. Each day I’ve played, I’ve also shared the result to WhatsApp. Just a habit, not a data strategy, but it turns out that habit quietly built a far more detailed record than Wordle itself ever keeps. One I can finally ask my own questions of. So I looked into rebuilding my own copy of the data.
- What's the most popular number in Hacker News titles?
Two consecutive titles on the HN front page yesterday had a 6 in them. This means nothing. But it’s the sort of nothing that lodges in your brain until you do something about it, so what is the most popular number in Hacker News titles?
Discussion
- 2014
- BF
Hi thought I’d post another solution. It’s pure javascript and extends Array (not required if you don’t want to)This is the fiddle if you’d like to play around. http://jsfiddle.net/spqr_pr…Array.prototype.groupItems = function() { var grouped = {}; for(var i = 0; i < this.length; i++){ grouped[this[i]] ? grouped[this[i]] += 1 : grouped[this[i]] = 1 } return grouped;}Thanks for your posts
Join the conversation
Reply from your own site with a Webmention (how?).
