Reputation: 258
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.
Upvotes: 0
Views: 42
Reputation: 1745
Array.push() return new length of the array after push
let arr =['A', 'B']
when you will push into this array.
arr.push('C') // return 3 . i.e. length of the array.
I think you don't want to push into splitHolder but concatenate the first element of splitArr .
function splitter(string, numSplit) {
let splitHolder = [];
let splitArr = string.split("");
while (!!splitArr.length) {
for (let i = 0; i < numSplit; i++) {
splitHolder[i] = (splitHolder[i] === undefined)
? [splitArr.shift()]
: splitHolder[i].concat(splitArr.shift());
console.log(splitHolder);
}
}
return splitHolder;
}
Upvotes: 0
Reputation: 386570
You could take Array#concat
instead of Array#push
.
concat
returns a new array and push
the new length of the array.
function splitter(string, numSplit) {
let splitHolder = [];
let splitArr = string.split("");
while (splitArr.length) {
for (let i = 0; i < numSplit; i++) {
splitHolder[i] = splitHolder[i] === undefined
? [splitArr.shift()]
: splitHolder[i].concat(splitArr.shift());
}
}
return splitHolder;
}
console.log(splitter('ABCABCABC', 3));
Upvotes: 1