I have a problem with grouping an array of numeric value:
I have values in an array like this
var numb = [5,10,11,6,7,18,1,8,2,1,15,12,4,5,3,4,6,7,15,20];
that are then sorted into ascending numerical order
var sortedNumb = [1,1,2,3,4,4,5,5,6,6,7,7,8,10,11,12,15,15,18,20];
Now I want to create a group of numbers like
1-4 , 5-8 , 9-12 , 13-16 , 17-20
Is it possible to create groups dynamically, like that?
Assuming that 1-4, 5-8, 9-12, 13-16, 17-20 grouping means that you want 5 groups, the first one (1-4) containing all the numbers within the [1, 4] interval; the second one (5-8) containing all the numbers within the [5, 8] interval, and so on.
The output:
EDIT: After reading the comment about calculating the intervals based on the max number in the array.
Output:
Code : Assuming sortedNumb is not empty :)
Output :
Edit :
You seemed to want a range of group of 4, if you want
N
, just create a function taking it as parameter, and replace all4
byN
in code =)This figures out the number of groups and then builds a dictionary of the groups using
Array.prototype.filter
.It only works with positive numbers.