0 like 0 dislike
16 views
There is an array of objects. How to group sequences so to speak. If the following element Id is greater by 1 than the sequence the same. If 2 more - that creates a new array and the elements are already there, and so on. If the Id of neighbors is greater than the Id of the element 2 - it will create an array with itself and the key equal to its Id. In other cases, the key will be the same as the first and last Id of the array elements.

You can use Lodash if you know a cunning method, or ligament. To me are not yet reach.

``const data = [ {id: 1}, {id: 2}, {id: 3}, {id: 4}, {id: 7}, {id: 9}, {id: 10}, {id: 12}, {id: 14}, {id: 15}, {id: 16}]; const result = [ "1-4": [ {id: 1}, {id: 2}, {id: 3}, {id: 4}], "7": [ {id: 7}], "9-10": [ {id: 9}, {id: 10}], "12": [ {id: 12}], "14-16": [ {id: 14}, {id: 15}, {id: 16}]];``
| 16 views

0 like 0 dislike
``const groups = []; data.forEach(n => { let g = groups[groups.length - 1]; if (!g || (n.id - g[g.length - 1].id > 1)) { g = []; groups.push(g); } g.push(n); }); const result = groups.reduce((r, g) => Object.assign(r, { [g.length === 1 ? g[0].id : `\${g[0].id}-\${g[g.length - 1].id}`]: g }), {});``
by
0 like 0 dislike
reduce
you can use as an option
by
0 like 0 dislike
I am still on stackoverflow this option wrote

``const result = data.reduce( ([result nextNum],item)=>{ if(nextNum===undefined){ nextNum=item.id; result.push([]); } if(!(nextNum===item.id)){ result.push([]); } result[result.length-1].push(item); return [result,item.id+1]; }, [[],undefined] );``
by

0 like 0 dislike