arrays - Grouping consecutive elements together using Javascript -


i have array of elements so:

messages[i], messages[i] may exist values of i. instance messages[0] , messages[2] may exist not messages[1].

now group elements continuous indices, example if indices messages existed were:

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

i group them so:

2, 3, 4, 5

8, 9

12, 13, 14, 15, 16, 17

20

what effective way using javascript?

edit:

for (i = 0; < messages.length; i++) {    if (messages[i].from_user_id == current_user_id) {    // group continuous messages       } else {   //group these continuous messages    } } 

you can use counter variable has incremented , difference between index , consecutive elements same, group them in temporary array. if difference varies 2 consecutive array elements, temporary element has moved result , temporary array has assigned new array object.

var array = [2, 3, 4, 5, 8, 9, 12, 13, 14, 15, 16, 17, 20];  var result = [], temp = [], difference; (var = 0; < array.length; += 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 ] ] 

Comments

Popular posts from this blog

user interface - How to replace the Python logo in a Tkinter-based Python GUI app? -

objective c - Greedy NSProgressIndicator Allocation -

how to set an OCR language in Google Drive -