# Counting Consecutive Elements of an Array in JavaScript

1. I see that my array’s first element is “a”. So I take note of that.
2. I look at the next element. It’s a “b”, which is not like my first. So, I should just make a mental note that my string should start with “a1”.
3. Now I’m looking at a “b”, and the following one is also a “b”, but the one after that is not a “b”, so I should make a mental note of “b2”.
4. Last one is “a”, so add “a1” to my mental note.
• I’m iterating
• I’m looking ahead of my current iteration
• I’m accumulating the number of times I’m seeing an element
• I’m adding it to a my mental note based on certain conditions
• A result string to house my answer
• A counter variable to count the number of times I’m seeing an element. I initialize the counter with 1.
`function cntConsecutiveElements(array) {  let result = "";  let counter = 1;}`
• 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) }`
• When i = 0, array[0] is “a”
• At line 5 we ask: is “a” = array[1]? Well, array[1] is “b”, so the answer is no.
• We hit the else statement in line 7 and concatenate “a” and 1 to form “a1”. We then add that to our result, which is now “a1”.
• Back to the top of the loop. When i = 1, array[1] is “b”.
• Again we ask: is “b” = array[2]? This time it is, so we increment our counter to 2.
• When i = 2, array[2] is “b” again.
• Again we ask: is “b” = array[3]. Array[3] is “a”, so the answer is no.
• We hit the else statement and concatenate “b” and 2 to form “b2”. We then add that to our result, which is now “a1b2”.
• When i = 3, array[3] is “a”.
• Again we ask: is “a” = array[4]? Well, array[4] is undefined. So definitely not. We hit the else statement and concatenate “a” and 1 to form “a1”. We then add that to our result, which is now “a1b2a1”.
• Iteration is now completed, and we return the string “a1b2a1”.

--

--

--

## More from Saul Feliz

Always learning.

Love podcasts or audiobooks? Learn on the go with our new app.

Always learning.