How to group data?


Warning: count(): Parameter must be an array or an object that implements Countable in /home/styllloz/public_html/qa-theme/donut-theme/qa-donut-layer.php on line 274
0 like 0 dislike
9 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}]];
by | 9 views

3 Answers

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

Related questions

0 like 0 dislike
3 answers
asked Aug 18, 2019 by Captain
0 like 0 dislike
1 answer
0 like 0 dislike
1 answer
0 like 0 dislike
2 answers
asked Jun 7, 2019 by draaax
0 like 0 dislike
1 answer
asked May 4, 2019 by KoNnY
110,608 questions
257,186 answers
0 comments
35,647 users