gpt4 book ai didi

javascript - 如何将数字列表转换为连续数字范围列表

转载 作者:行者123 更新时间:2023-11-28 12:25:05 27 4
gpt4 key购买 nike

我正在生成一个数字列表:

[1,2,3,4,6,7,8,9,11,12,13,14,16,17,18,19]

请注意一些数字是如何缺失的(在本例中,每五个数字)。我想将连续数字转换为范围,用破折号分隔。

在上述情况下,我希望输出为

"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;
}

这将返回一个数组数组:

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”

提示:使用Array.prototype.mapArray.prototype.join

关于javascript - 如何将数字列表转换为连续数字范围列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29976532/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com