不规则json数组,组合成新string数据(轻微烧脑3种解法)

130 阅读3分钟

##场景为数据生成二维码,如数据量过多二维码会复杂,因此通过约定进行重组更改

["a", "s", "d", "1", "2", "3", "5", "6", "h6", "9", "12", "13", "14", "15", "f", "g"] 这种数组,怎么组合成: "a;s;d;1-3;5-6;h6; 9;12-15;f;g" 解释:连续的正整数用横杠连接,不相的单独表示,这样可以节约数字占用的空间,12-15代表12至15,节省了13,14,如果是1-90呢,就大大节约了空间. 大家最好先别看下面的解题方式,先自己试试,再看解决代码,受益良多

三位大佬给出了解决方案,思路清晰,方式不同

1.最精简版本

let data = ['a', 's', 'd', '1', '2', '3', '5', '6', 'h2', '9', '12', '13', '14', '15', 'f', 'g']
        let i = 0,
            m = i + 1,
            result = [];

        while (i < data.length) {
            const d = data[i];
            if (data[m] - data[m - 1] == 1) {
                m++
            } else {
                result.push(m - 1 > i ? data[i] + '-' + data[m - 1] : data[i])
                i = m
                m = m + 1
            }
        }
        console.log(result.join(';'));
//a;s;d;1-3;5-6;h2;9;12-15;f;g

2.第二版本

let data = ['a1', 's2','d3', '1', '2', '3','h8', '5', '6', '9', '12', '13', '14', '15', 'f', 'g'];
      let save = [];
      data.forEach(i => {
        if (isNaN(i))                      //判断是否为非数字
          return save.push(i);              //如果是非数字,push进数组,跳出循环
        
        let last = save[save.length - 1];   //查save数组最后一位是数字的数组还是非数字
  
        i = parseInt(i);                    //当前循环到的数字转型
  
        if (last instanceof Array && i - last[last.length - 1] == 1)   //如果是数字数组,并且当前循环的数字减去数组最后一位等于1,表明是相邻的数字
          return last.push(i)             //满足条件就将当前循环的数字push进数组,跳出循环
        
  
        save.push([i])                    //不满足上面条件说明当前循环的数字是断层,push当前循环的数字为一个单独数组
      })
            //遍历生成的新数组,如果是字母就不变,是数组的话取第一位-最后一位,以;为分割线
      console.log(save.map(i => i instanceof Array ? (i.length > 1 ? i[0] + '-' + i[i.length - 1] : i[0]) : i).join(';'))

3.解决问题版本

let test = ['a','s','d','1','2','3','5','6','9','12','13','14','15','f','g'],
    gap = 1, 
    out = [],
    compute = [],
    lastNum = 1


test.forEach((item,index) =>{
    +item >= 0 ? compute.push(item) : out.push(item)  
    if (compute.length > 1 ) {
        if (compute[1] - compute[0] === gap &&  +test[index + 1] >= 0) {
            gap++ 
            lastNum = compute[1] 
            compute.length = 1
        }else {
            if (gap === 1){
                out.push(compute[0]) 
                compute = compute.slice(compute.length - 1)
            }
            else{
                gap = 1 
                lastNum = +test[index + 1] >= 0 ? lastNum : compute[1]
                out.push(compute[0] + '-' + lastNum) 
                compute = compute.slice(compute.length - 1)
            }
        }
    }
})
console.log(out.join(';'))