JS把数组中相同元素组合成一个新的数组问题
现在有一个这样规律的数组,需求是把里面相同元素组合成一个新的数组,有什么比较简便的方法不
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" ] ]*/