问题描述
我有一个像这样的元素数组:
I have an array of elements like so:
messages[i]
,其中messages[i]
仅对i
的某些值存在.例如,messages[0]
和messages[2]
可能存在,但messages[1]
不存在.
messages[i]
, where messages[i]
may only exist for certain values of i
. For instance messages[0]
and messages[2]
may exist but not messages[1]
.
现在,我想将具有连续索引的元素组合在一起,例如,如果存在消息的索引是:
Now I would like to group together elements with continuous indices, for example if the indices for which messages existed were:
2, 3, 4, 5, 8, 9, 12, 13, 14, 15, 16, 17, 20
我想像这样对它们进行分组:
I would like to group them like so:
2, 3, 4, 5
8, 9
12, 13, 14, 15, 16, 17
20
使用Java脚本执行此操作的有效方法是什么?
What would be an effective way to do so using Javascript?
for (i = 0; i < messages.length; i++) {
if (messages[i].from_user_id == current_user_id) {
// group the continuous messages together
} else {
//group these continuous messages together
}
}
推荐答案
您可以使用必须递增的计数器变量,并且索引和连续元素之间的差异相同,将它们分组在一个临时数组中.如果两个连续的数组元素的差异有所不同,则必须将临时元素移到result
,并且必须为该临时数组分配一个新的数组对象.
You can use a counter variable which has to be incremented and the difference between the index and the consecutive elements are the same, group them in a temporary array. If the difference is varies for two consecutive array elements, the temporary element has to be moved to the result
and the temporary array has to be assigned a new array object.
var array = [2, 3, 4, 5, 8, 9, 12, 13, 14, 15, 16, 17, 20];
var result = [], temp = [], difference;
for (var i = 0; i < array.length; i += 1) {
if (difference !== (array[i] - i)) {
if (difference !== undefined) {
result.push(temp);
temp = [];
}
difference = array[i] - i;
}
temp.push(array[i]);
}
if (temp.length) {
result.push(temp);
}
console.log(result);
# [ [ 2, 3, 4, 5 ], [ 8, 9 ], [ 12, 13, 14, 15, 16, 17 ], [ 20 ] ]
这篇关于使用Javascript将连续元素分组在一起的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!