I have been trying to solve this problem for some time now and I have partially managed to achieve it.
I am trying to write a function that will return a nested array, each array element will contain the number of consecutive chars found in a given string.
For example: for the given string “aaaabccaadeeee”, the function should return nested array [[4, a] [1, b] [2, c] [2, a] [1, d][4, e]]
I have managed to write the following function but it returns [ [ 4, ‘b’ ], [ 0, ‘c’ ], [ 1, ‘a’ ], [ 1, ‘d’ ], [ 0, ‘e’ ] ]
What am I doing wrong?
function consecutiveArray(str) { const chunks = str.split(""); let counter = 0; const finalArray = []; let prevItem; for(chunk of chunks){ if(!prevItem || prevItem === chunk){ counter++ } else { finalArray.push([counter, chunk]) counter=0; } prevItem = chunk; } return finalArray; } console.log(consecutiveArray('aaaabccaadeeee'))
Advertisement
Answer
Your else
clause is wrong, you should push the counter for prevItem
and initialize the count to 1
. Also, push the final counter the after the loop.
function consecutiveArray(str) { const chunks = str.split(""); let counter = 0; const finalArray = []; let prevItem; for(chunk of chunks){ if(!prevItem || prevItem === chunk){ counter++ } else { finalArray.push([counter, prevItem]) counter=1; } prevItem = chunk; } finalArray.push([counter, prevItem]) return finalArray; } console.log(consecutiveArray('aaaabccaadeeee'))