记录一段js:判断数组元素连续或者不连续

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Amy_cloud/article/details/86294831

如果我们拿到一个数组的解构是这样的:
[‘2’,‘3’,‘5.5’,‘6’,‘7’,‘8’,‘12’,‘12.1’,‘13’,‘16’,‘17’]
我们需要把它变成这样:
2-3,5.5,6-8,12,12.1,13,16-17

思路:
1,先将数组连续的数字push进一个新的数组
2,再通过 map 遍历这个数组

function sort(arr) {
    var result = [];
    arr.forEach(function (v, i) {
        var temp = result[result.length - 1];
        if (!i) {
            result.push([v]);
        } else if (v % 1 === 0 && v - temp[temp.length - 1] == 1) {
            temp.push(v);
        } else {
            result.push([v]);
        }
    });
    console.log(result);
    return result.map(function (v) {
        if (v.length == 1) {
            return v;
        } else {
            return v[0] + '-' + v[v.length - 1];
        }
    }).join(",");
}

猜你喜欢

转载自blog.csdn.net/Amy_cloud/article/details/86294831
今日推荐