使用Javascript将连续元素分组在一起

gee*_*hic 6 javascript arrays

我有一个像这样的元素数组:

messages[i],messages[i]可能只存在某些值的i.例如messages[0],messages[2]可能存在但不存在messages[1].

现在我想将具有连续索引的元素组合在一起,例如,如果存在消息的索引是:

2, 3, 4, 5, 8, 9, 12, 13, 14, 15, 16, 17, 20

我想像他们这样分组:

2, 3, 4, 5

8, 9

12, 13, 14, 15, 16, 17

20

使用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
   }
}
Run Code Online (Sandbox Code Playgroud)

the*_*eye 4

您可以使用必须递增的计数器变量,并且索引和连续元素之间的差异相同,将它们分组在临时数组中。如果两个连续数组元素的差异不同,则必须将临时元素移动到 ,result并且必须为临时数组分配一个新的数组对象。

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 ] ]
Run Code Online (Sandbox Code Playgroud)