如何将数字数组转换为一个范围?[1,2,3,4,5]->"1~5"

简单的写了个方法,可以将数字的数组转换为一个范围。
处理了一些异常的情况,诸如数字重复,异常数字等问题。

仅供参考:

/**
 * Converts an array of numbers to a range string.
 *    - If there are non numeric parts in the passed in parameter array, they will be placed at the end of the whole array in the original order.
 *
 *    [1,2,5,7,9,10,12,11,8,3,4] -> ['1~5','7~12']
 *    [1,4] -> ['1','4']
 *    [1,1,1,1,2,3,4,5] -> ['1','1','1','1~5']
 *    [1] -> ['1']
 *    [1,"a","b","ccc","1","2","3"] -> ['1','1~3','a','b','ccc']
 *    [] -> []
 *
 * @param nums
 */
export function convertNumberArrayToRange(nums: any[]) {
  try {
    let numArray = [];
    const notNumArray = [];
    for (let i = 0; i < nums.length; i++) {
      const item = nums[i];
      if (isNaN(item)) {
        notNumArray.push(item);
      } else {
        numArray.push(Number.parseInt(item));
      }
    }
    numArray = numArray.sort((a, b) => {
      return a - b;
    });
    let ranges = [],
      start,
      end;
    for (let i = 0; i < numArray.length; i++) {
      start = numArray[i];
      end = start;
      while (numArray[i + 1] - numArray[i] == 1) {
        end = numArray[i + 1];
        i++;
      }
      ranges.push(start == end ? start + '' : start + '~' + end);
    }
    ranges = ranges.concat(notNumArray);
    return ranges;
  } catch (e) {
    console.log(e);
    return nums.join(',');
  }
}
posted @ 2022-05-09 15:31  刘伟佳  阅读(96)  评论(0)    收藏  举报