如何将数字列表转换为连续数字范围列表 [英] How to transform a list of numbers into a list of ranges of consecutive numbers
本文介绍了如何将数字列表转换为连续数字范围列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在生成一个数字列表:
I'm generating a list of numbers:
[1,2,3,4,6,7,8,9,11,12,13,14,16,17,18,19]
注意如何缺少一些数字(在这种情况下,每5个数字)。我想将连续数字转换为范围,用短划线分隔。
Note how some numbers are missing (in this case, every 5th number). I want to transform consecutive numbers into ranges, delimited by a dash.
在上面的例子中,我希望输出为
In the above case, I'd like the output to be
"1-4,6-9,11-14,16-20"
我如何解决这个问题?
推荐答案
var convertToRanges = function (str) {
// split the string at the commas and map it to an array of ints
// NOTE: if you are passing an array, skip this step
var pieces = str.split(",").map(Number)
// ranges will be an array of arrays
// each inner array will have 2 dimensions, representing the start/end
// of a range
// we want to initialize our first range to pieces[0], pieces[0],
// or (only the first element)
, ranges = [[pieces[0], pieces[0]]]
// last index we accessed (so we know which range to update)
, lastIndex = 0;
for (var i = 1; i < pieces.length; i++) {
// if the current element is 1 away from the end of whichever range
// we're currently in
if (pieces[i] - ranges[lastIndex][1] === 1) {
// update the end of that range to be this number
ranges[lastIndex][1] = pieces[i];
} else {
// otherwise, add a new range to ranges
ranges[++lastIndex] = [pieces[i], pieces[i]];
}
}
return ranges;
}
这将返回一个数组数组:
This will return an array of arrays:
console.log(convertToRanges("1,2,3,4,6,7,8,9,11,12,13,14,16,17,18,19"));
// -> [ [1, 4], [6, 9], [11, 14], [16, 19] ]
我会留给你弄清楚如何将其转换为1-4,6-9,11-14,16-20
I'll leave it to you to figure out how to transform this to look like "1-4,6-9,11-14,16-20"
提示:使用 Array.prototype.map
和 Array.prototype.join
这篇关于如何将数字列表转换为连续数字范围列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文