刚才一朋友问了我一个问题:
arr=['1','1','1','2',,'3','4','5','5','6','6','7','8','9','9','10'];现在有一个这样规律的数组,需求是把里面相同元素组合成一个新的数组,有什么比较简便的方法不
也就是说,最终要的结果是这样的:
newArr = [ [ "1" , "1" , "1" ] , [ "2" ] , [] , [ "3" ] , [ "4" ] , [ "5" , "5" ] , [ "6" , "6" ] , [ "7" ] , [ "8" ] , [ "9" , "9" ] , [ "10" ] ]
我的方案如下:
var arr=['1','1','1','2',,'3','4','5','5','6','6','7', '8','9','9','10']; var newArr = [], tempArr = []; for(var i=0,j=arr.length;i<j;i++){ if(arr[i] == arr[i+1]){ tempArr.push(arr[i]); } else { tempArr.push(arr[i]); newArr.push(tempArr.slice(0)); tempArr.length = 0; } } console.log(newArr); /*[ [ "1" , "1" , "1" ] , [ "2" ] , [] , [ "3" ] , [ "4" ] ,[ "5" , "5" ] , [ "6" , "6" ] , [ "7" ] , [ "8" ] , [ "9" , "9" ] , [ "10" ] ]*/
对此问题,大家有无更好算法,欢迎分享。