如何在数字排序列表中合并连续数字? [英] How do I merge consecutive numbers in a sorted list of numbers?

查看:199
本文介绍了如何在数字排序列表中合并连续数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在可读字符串中连接数字序列。连续数字应该像这样'1-4'合并。

I want to concatenate a sequence of numbers in a readable string. Consecutive numbers should be merged like this '1-4'.

我可以用将所有数字组合成一个完整的字符串,但是我在合并/合并连续数字时遇到了麻烦。

I'm able to concatenate an array with all the numbers into a complete string but I'm having trouble combining / merging consecutive numbers.

我尝试将循环中的前一个和下一个值与当前值进行比较几个 if 条件,但我似乎找不到合适的条件来使其正常工作。

I tried comparing the previous and next values with the current one in the loop with several if-conditions but I couldn't seem to find the right ones to make it work properly.

示例:

if(ar[i-1] === ar[i]-1){}
if(ar[i+1] === ar[i]+1){}

我的代码如下:

var ar = [1,2,3,4,7,8,9,13,16,17];

var pages = ar[0];
var lastValue = ar[0];

for(i=1; i < ar.length; i++){
      if(ar[i]-1 === lastValue){
          pages = pages + ' - ' + ar[i];
      }else{
          pages = pages + ', ' + ar[i];
      }
}

alert(pages);

结果是: 1-2、3、4、7、8、9、13、16、17

最后它应该看起来像这样: 1-4、7-9、13、16-17

In the end it should look like this: 1-4, 7-9, 13, 16-17.

编辑:
我在@CMS'链接中为脚本使用了第一个答案。看起来很像@corschdi的代码段的较短版本:

I used the first answer at @CMS' link for my Script. Looks pretty much like a shorter version of @corschdi's snippet:

var ar = [1,2,3,4,7,8,9,13,16,17];


var getRanges = function(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;
}


alert(getRanges(ar));

推荐答案

这应该起作用:

var array = [1, 2, 3, 4, 7, 8, 9, 13, 16, 17];

var ranges = [];
var index = 0;
while (index < array.length) {
    var rangeStartIndex = index;
    while (array[index + 1] === array[index] + 1) {
        // continue until the range ends
        index++;
    }

    if (rangeStartIndex === index) {
        ranges.push(array[index]);
    } else {
        ranges.push(array[rangeStartIndex] + " - " + array[index]);
    }
    index++;
}

console.log(ranges.join(", "));

这篇关于如何在数字排序列表中合并连续数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆