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]
Tiny ES6 module for you guys. It accepts a function to determine when we must break the sequence (breakDetectorFunc param - default is the simple thing for integer sequence input). NOTICE: since input is abstract - there's no auto-sorting before processing, so if your sequence isn't sorted - do it prior to calling this module
first argument is the input sequence sorted array, second is a boolean flag controlling the output mode: if true - single item (outside the intervals) will be returned as arrays anyway: [1,7],[9,9],[10,10],[12,20], otherwise single items returned as they appear in the input array
for your sample input
it will return:
I needed TypeScript code today to solve this very problem -- many years after the OP -- and decided to try a version written in a style more functional than the other answers here. Of course, only the parameter and return type annotations distinguish this code from standard ES6 JavaScript.
Note that
slice
is necessary becausesort
sorts in place and we can't change the original array.Just having fun with solution from CMS :
Using ES6, a solution is:
If you want to add extra spaces for readability, just add extra calls to
string.prototype.replace()
.If the input vector is not sorted, you can add the following line right after the opening brace of the
display()
function:vector.sort ( ( a, b ) => a - b ); // sort vector in place, in increasing order
.Note that this could be improved to avoid testing twice for integer adjacentness (adjacenthood? I'm not a native English speaker;-).
And of course, if you don't want a single string as output, split it with ";".
I was just looking for this exact thing. I needed a PHP version so ported CMS's solution. Here it is, for anyone who stops by this question looking for the same thing:
Here's what I put together in Swift. It eliminates duplicates and sorts the array first, and doesn't mind if it's given an empty array or an array of one.