# Counting Consecutive Elements of an Array in JavaScript

I failed the interview question. Let’s make sure we both learn a lesson.

I recently had a tech interview where I was asked this question:

Given an array of characters return a string that counts the number of each consecutive letter.

Example: [“a”, “b”, “b”, “a”] should return “a1b2a1”

Seems simple enough. I’m sure a nested for loop…

Maybe it was nerves. But I simply couldn’t figure it out in the allotted 20 minutes. After licking my wounds, I got back up on that horse, and looked at it with fresh eyes with the help of a friend. It now seemed so simple.

I think my major flaw in the interview is that I didn’t follow my own advice: do it as a human first. Take notes of what I did. Pseudocode that. Then translate to code. Let’s do that here (practice makes perfect, right?):

1. I see that my array’s first element is “a”. So I take note of that.

This is how I naturally do it. And I can immediately tell that,

• I’m iterating

Let’s start translating this to code. First I’m going to initialize a couple of variables:

• A result string to house my answer
`function cntConsecutiveElements(array) {  let result = "";  let counter = 1;}`

Next we iterate. A simple for loop will suffice. Let’s try with the example: [“a”, “b”, “b”, “a”]

• The first element I see will start with a counter of 1. If the following element is the same as the one I’m currently iterating with, I should increment my counter:
`function cntConsecutiveElements(array) {  let result = "";  let counter = 1;for (let i = 0; i < array.length; i++) {    if (array[i] === array[i + 1]) {      counter++;    }   }  return result;}`
• If it’s not, then I should add the element, and the counter together, and then add that to my result. After iterating is complete, I should return the result:
`(1) function cntConsecutiveElements(array) {(2)   let result = "";(3)   let counter = 1;(4) for (let i = 0; i < array.length; i++) {(5)    if (array[i] === array[i + 1]) {(6)      counter++;(7)    } else {(8)      result += array[i] + counter;(9)      counter = 1;(10)    }(11)  }(12)   return result;(13) }`

Let’s walk through the code with our example:

• When i = 0, array is “a”

It was a bit disheartening to receive this relatively simple interview question, and not be able to knock it out of the park. But this is why I always say…

Grit > talent

I’ll get it next time :-)