减少javascript中的范围的最佳方法是什么。
例如,我有
1-3,4-5,10-12,2-4我需要的结果是
1-5, 10-12解决这个问题的最好方法是什么?
发布于 2014-05-27 11:08:34
首先,我将创建另一个没有重复项的数组,存储范围所涵盖的数字:
1-3 covers 1, 2, 3 --> [1, 2, 3]
4-5 covers 4, 5 --> [1, 2, 3, 4, 5]
10-12 covers 10, 11, 12 --> [1, 2, 3, 4, 5, 10, 11, 12]
2-4 covers 2, 3, 4 --> [1, 2, 3, 4, 5, 10, 11, 12]然后,对数组排序:
[1, 2, 3, 4, 5, 10, 11, 12] // nothing changed in this example最后,根据连续的值重新构建范围:
1-5
10-12发布于 2014-05-27 11:21:10
1)解析输入以构建如下结构:
var rlist = [
{min: 1, max: 3},
{min: 4, max: 5},
{min: 10, max: 12}
{min: 2, max: 4}
];2)将该列表的每一个间隔划分为一个新的列表:
var olist = [], i, j, r, p, s;
for (i = 0; i < rlist.length; ++i) {
r = rlist[i];
for (j = 0; j < olist.length; ) {
p = olist[j];
if (r.max+1 < p.min) {
// insert here
break;
} else if (p.max+1 >= r.min) {
// intersection
olist.splice(j, 1);
r.min = p.min;
r.max = Math.max(r.max, p.max);
} else {
++j;
}
}
olist.splice(j, 0, r);
}3)将结果转换为字符串
s = "";
for (j = 0; j < olist.length; ++j) {
if (j > 0) {
s += ",";
}
s += olist[j].min + "-" + olist[j].max;
}小提琴
https://stackoverflow.com/questions/23887686
复制相似问题