如何将数组中的连续整数减少为连字符范围表达式?
在 JavaScript 中,如何将数组中的数字序列转换为数字范围?换句话说,我想将连续出现的整数(无间隙)表示为连字符范围.
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]
将变为 [2-5,10,18-20]
[1,6,7,9,10,12]
会变成 [1,6-7,9-10,12]
[3,5,99]
将保持 [3,5,99]
[5,6,7,8,9,10,11]
将变为 [5-11]
推荐答案
这是我自己做的一个算法前段时间,最初是为 C# 编写的,现在我将其移植到 JavaScript:
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"]
相关文章