I would like to know how to combine two or more adjacent elements of an array.
For example, I have an array arr = ['a','bb','ccc','d','e','f','g','hhhhhhhh']
and I want to concatenate some elements to make it ['a','bb', 'ccc', 'defg','hhhhhhhh']
. Specifically, I want to do the following: if an element's length is less than its index plus one, I want to concatenate it with the element that follows, eliminating the element that follows. (I.e., for this example, because arr[3].length
<= 3+1, it gets concatenated with the elements that follow it until arr[3].length == 3+1
.) I'll be executing this from inside a loop, and working from left to right in the array.
Is there any easy way to do this in JavaScript?
Thanks!
Just turn your English into JavaScript:
for (var i = 1; i < array.length - 1; i++) { // I want to concatenate the middle elements
while (array[i].length <= i && typeof array[i + 1]!='undefined' ) { //if an element's length is less than or equal to its index
array[i] += array[i + 1]; //I want to concatenate it with the element that follows
array.splice(i + 1, 1); //eliminating the element that follows
}
}
See it in action:
var array = ['a', 'bb', 'ccc', 'd', 'e', 'f', 'g', 'hhhhhhhh'];
for (var i = 1; i < array.length - 1; i++) {
while (array[i].length <= i && typeof array[i + 1]!='undefined' ) {
array[i] += array[i + 1];
array.splice(i + 1, 1);
}
}
alert(array.join(', '));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With