可以为您完成工作的oneliner将是:
var input = [1,1,1,2,2,2,0,0,0,1,1,1];
var output = (input.join(',')+',').match(/(\d*,)\1+/g).map(function(str){return str.replace(/,$/,'').split(',').map(Number);})
基本上它的作用:
(input.join(',') + ',') // concatenate all numbers with a ',', and add a trailing comma to help the matching
.match(/(\d*,)\1+/g) // match groups of numbers of the same type with comma ( "1,1,2," > ["1,1", "2,"] ). The * is to support null/undefined values in the original array
.map( // replace every match (only works in modern browsers, but you can replace it with _.map )
function() {
return str.replace(/,$/, '') // remove trailing ', '
.split(',') // and split the string by , "1,1,1" > [1,1,1]
.map(Number) // map everything back to Number (converts undefined / null values to 0 as a sideeffect, but keeps them as a group
}
);
如果您不想依赖map
仅由现代浏览器提供的可用性,您可以像这样使用下划线映射:
var input = [1,1,1,2,2,2,0,0,0,1,1,1];
var output = _.map((input.join(',')+',').match(/(\d*,)\1+/g), function(str){ return _.map(str.replace(/,$/,'').split(','), Number);});
软件
正如在 Xotic750 进行的 jsperf 分析中可见的那样,这是性能最低的解决方案。我只是将其列为替代方法,也许是最短的方法。