Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: how to combine two adjacent elements of an array

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!

like image 715
jayqui Avatar asked Sep 08 '25 08:09

jayqui


1 Answers

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(', '));
like image 85
Shomz Avatar answered Sep 10 '25 11:09

Shomz