i am dustin diaz

a JavaScriptr...

boosh.

don't worry about it.

Programming Brain Teaser

I've titled this post as a "Programming" brain teaser because ideally you could solve it in any language. For the sake of the exercise, I'm going to show sample code in JavaScript, but feel free to use your language of choice. But first and foremost, the reason I'm writing about this is because I ran into a logic problem last week which I thought I would be able to solve in two seconds. Sadly it wasn't the case so I'd like to share that same problem (in obfuscated form) with you, the readers. I know what you're thinking. You're at work, and you've got a few minutes to whip up a simple answer. Cool then, go for it. Be sure to share your answer with the rest of us by linking to it offsite, but do not share code in the comments directly as others will most likely want to solve it themselves.

The problem is simple

First, you have an array. It looks like this:

The array



var arr = ['a', 'b', 'c', 'c', 'd','e', 'e', 

'e', 'e', 'e', 'f', 'e', 'f', 'e', 

'f', 'a', 'a', 'a', 'f', 'f', 'f'];

Be sure to use the array above in your example. You can iterate through an array easily with a batch function like forEach.

using forEach

arr.forEach(funciton(item, index, ar) {

  // do stuff here

});
In the end, we'd like to have an output that looks like the following:

The final output



a b c c d e e <span>e e e</span> f e f e f a a <span>a</span> f f <span>f</span>
You can use basic string concatenation while looping through the items to build your final output. Be sure to test and compare your output results with the actual results. And last but not least, the rule.

So the rule is this

In English: Group together all duplicate items that occur anytime beyond twice by wrapping them with a tag, naturally "bookending" them.

Simple, right? No, really. Tease your brain for a few minutes, you can fix that bug after lunch.

this is who i am

Hi, my name is Dustin Diaz and I'm an Engineer @ObviousCorp. Previously @Twitter, @Google, and @Yahoo, author of Strobist® Info co-author of JavaScript Design Patterns, co-creator of the Ender JavaScript Framework, a Photographer, and an amateur Mixologist. This is my website. Welcome!

On this site I write about JavaScript. You can also follow along with my open-source work on Github.

This site is optimized and works best in Microsoft Internet Explorer 6.