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
1 Answer
Reset to default 11Just 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
版权声明:本文标题:Javascript: how to combine two adjacent elements of an array - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741292230a2370619.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论