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]
Something like that.
Here's my take on this...
PHP
I've written my own method that's dependent on Lo-Dash, but doesn't just give you back an array of ranges, rather, it just returns an array of range groups.
[1,2,3,4,6,8,10] becomes:
http://jsfiddle.net/mberkom/ufVey/
If you simply want a string that represents a range, then you'd find the mid-point of your sequence, and that becomes your middle value (10 in your example). You'd then grab the first item in the sequence, and the item that immediately preceded your mid-point, and build your first-sequence representation. You'd follow the same procedure to get your last item, and the item that immediately follows your mid-point, and build your last-sequence representation.
Demo Online: http://jsbin.com/uvahi/edit