I am trying to split a string and combine it based on its index. A trivial example will be:
Input: "ABCABCABC" Output: "AAABBBCCC"
So I created a function that converts the string into an array pops off the elements into its appropriate array and hopefully combine it back to a string.
Here's the function:
function splitter(string, numSplit) {
let splitHolder = [];
let splitArr = string.split("");
while (splitArr.length > 0) {
for (let i = 0; i < numSplit; i++) {
splitHolder[i] = splitHolder[i] === undefined
? [splitArr.shift()]
: splitHolder[i].push(splitArr.shift());
console.log(splitHolder);
}
}
}
Results for the console.log shows:
[ [ 'A' ] ]
[ [ 'A' ], [ 'B' ] ]
[ [ 'A' ], [ 'B' ], [ 'C' ] ]
which indicates the function is running okay at least on the first loop. However on the second pass of the for loop after it is checked by the while. I am getting this log:
[ 2, [ 'B' ], [ 'C' ] ]
[ 2, 2, [ 'C' ] ]
[ 2, 2, 2 ]
Which is very strange as I am still trying to push what is remaining of the array? Where did the numeric 2 come from?
Initially thought it was a scoping issue but it wasn't as the let is scoped for the whole function.
Also tried the array reduce function but am still getting the same numeric 2.
'ABCABCABC'.split('').sort().join('')Array#pushreturns the new length of the array, and you're doingsplitHolder[i] = splitHolder[i].push(...);Just use anifstatement like everybody else.