In javascript how to convert sequence of numbers in an array to range of numbers?
eg. [2,3,4,5,10,18,19,20]
to [2-5,10,18-20]
In javascript how to convert sequence of numbers in an array to range of numbers?
eg. [2,3,4,5,10,18,19,20]
to [2-5,10,18-20]
An adaptation of CMS's javascript solution for Cold Fusion
It does sort the list first so that
1,3,2,4,5,8,9,10
(or similar) properly converts to1-5,8-10
.I found this answer useful, but needed a Python version:
You could iterate over the numbers and see if the next number is 1 bigger then the current number. So have a:
where if
array[i+1] == array[i]+1;
(where i is the currently observed number) thenrange.end = array[i+1];
. Then you progress to the nexti
; Ifarray[i+1] != array[i]+1;
thenrange.end = array[i];
you could store the ranges in a
vector< range > ranges;
printing would be easy:
Here is an algorithm that I made some time ago, originally written for C#, now I ported it to JavaScript:
Here is a port of CMS's code for BASH:
Here is a version for Perl: