In JavaScript, how can I convert a sequence of numbers in an array to a range of numbers? In other words, I want to express consecutive occurring integers (no gaps) as hyphenated ranges.
[2,3,4,5,10,18,19,20]
would become [2-5,10,18-20]
[1,6,7,9,10,12]
would become [1,6-7,9-10,12]
[3,5,99]
would remain [3,5,99]
[5,6,7,8,9,10,11]
would become [5-11]
1) Sort all the elements. 2) Do a linear scan of the sorted array. If the difference between the current element and the next element is anything other than 1, then return false. If all differences are 1, then return true.
Range of a set of numbers is the difference of highest number & the lowest number . Consecutive integers are a set which when arranged in ascending or descending order , the common difference of any two consecutive number is 1.
Here is an algorithm that I made some time ago, originally written for C#, now I ported it to JavaScript:
function getRanges(array) { var ranges = [], rstart, rend; for (var i = 0; i < array.length; i++) { rstart = array[i]; rend = rstart; while (array[i + 1] - array[i] == 1) { rend = array[i + 1]; // increment the index if the numbers sequential i++; } ranges.push(rstart == rend ? rstart+'' : rstart + '-' + rend); } return ranges; } getRanges([2,3,4,5,10,18,19,20]); // returns ["2-5", "10", "18-20"] getRanges([1,2,3,5,7,9,10,11,12,14 ]); // returns ["1-3", "5", "7", "9-12", "14"] getRanges([1,2,3,4,5,6,7,8,9,10]) // returns ["1-10"]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With