admin管理员组

文章数量:1277309

I would like to know how to bine 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!

I would like to know how to bine 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!

Share Improve this question edited Jan 27, 2015 at 16:03 jayqui asked Jan 27, 2015 at 15:50 jayquijayqui 1,8992 gold badges20 silver badges20 bronze badges 1
  • 1 Array.prototype.splice – Evan Davis Commented Jan 27, 2015 at 15:53
Add a ment  | 

1 Answer 1

Reset to default 11

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(', '));

本文标签: Javascript how to combine two adjacent elements of an arrayStack Overflow