-2

我有以下数组:arrtooth

var arrtooth = tooth.split('|');

它获得了价值

arrtooth=[1,2,3,6,7,10,11,15,16,17];

我想要按顺序排列的元素(1,2,3) (6,7) (10,11) (15,16,17)。分开。我的代码在 Jquery 中。我只想要实际的逻辑。

如果我在一个数组中得到 3 2 2 3 的输出,那会很好,或者如果你有任何可以详细说明序列的东西(输出)就可以了。

4

3 回答 3

2
var arrtooth = [1, 2, 3, 6, 7, 10, 11, 15, 16, 17];
var last = arrtooth[0];
var result = [];
count = 1;
for (var i = 1; i < arrtooth.length; i++) {
    if (arrtooth[i] == (last + 1)) {
        count++;

    } else {
        result.push(count);
        count = 1;
    }
    last = arrtooth[i];
}
result.push(count);

jsFiddle 示例

于 2013-04-05T14:15:28.817 回答
0
var arrtooth=[1,2,3,6,7,10,11,15,16,17];

var a = arrtooth.reduce(function(result, cur,index, array){
     if( index == 0 || array[index-1] + 1 !== cur ){
        result.push(0);
     }
     result[ result.length-1 ]++;
     return result;
},[]);

console.log(a);   //[3,2,2,3];

演示

于 2013-04-05T14:13:14.770 回答
0

假设数组包含以其他方式排序的整数,以下两个函数将为您提供您所追求的连续子集。第一个产生一个字符串输出,第二个产生一个二维数组。

var arrtooth = [1, 2, 3, 6, 7, 10, 11, 15, 16, 17];

function stringOutput(arrtooth) {
    var outputString = '(';
    for (var i = 0; i < arrtooth.length; i++) {
        if (i === 0) outputString += arrtooth[i];
        else if (arrtooth[i] - 1 == arrtooth[i - 1]) outputString += ',' + arrtooth[i];
        else outputString += ') (' + arrtooth[i];
    }
    outputString += ')';
    return outputString;
}

function arrayOutput(arrtooth) {
    var outputArray = [],
        toothArray = [];
    for (var i = 0; i < arrtooth.length; i++) {
        if (i === 0 || arrtooth[i] - 1 != arrtooth[i - 1]) {
            toothArray = [];
            outputArray.push(toothArray);
        }
        toothArray.push(arrtooth[i]);
    }
    return outputArray;
}

jsFiddle 演示

于 2013-04-05T14:13:27.950 回答