将一个js的数组,按要求分割为一个有规律的几组。

var arr=[1,1,2,2,2,1,1,3,3,1];

分割为:var newArr=[[[1,1],[1,1],[1]],[2,2,2],[3,3]]

求一个思路,数据量很大,并且要求只能用一个for


ibeautiful
浏览 1518回答 3
3回答

阿波罗的战车

var arr=[1,1,2,2,2,1,1,3,3,1];m = new Map();i = 0;for(var j=1;j<arr.length;j++){&nbsp; &nbsp; if(arr[j] != arr[i]){&nbsp; &nbsp; &nbsp; &nbsp; if(m.has(arr[i])){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; m.get(arr[i]).push(arr.slice(i, j));&nbsp; &nbsp; &nbsp; &nbsp; }else{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; m.set(arr[i], [arr.slice(i, j)]);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; i = j;&nbsp; &nbsp; }}&nbsp; &nbsp;//一次循环复杂度O(n)if(m.has(arr[i])){&nbsp; &nbsp; m.get(arr[i]).push(arr.slice(i));}else{&nbsp; &nbsp; m.set(arr[i], [arr.slice(i)]);}res = [];m.forEach((o)=>{&nbsp; &nbsp; if(o.length == 1){&nbsp; &nbsp; &nbsp; &nbsp; res.push(o[0])&nbsp; &nbsp; }else{&nbsp; &nbsp; &nbsp; &nbsp; res.push(o)&nbsp; &nbsp; }})&nbsp; &nbsp; //一次循环复杂度O(m) m远小于n所以最终复杂度O(n)

撒科打诨

// 抛个砖.var arr = [1, 1, 2, 2, 2, 1, 1, 3, 3, 1];var map = {};var result = [];arr.forEach((el, ind) => {&nbsp; if (map[el]) {&nbsp; &nbsp; if (ind - map[el].ind > 1) {&nbsp; &nbsp; &nbsp; map[el].ind = ind;&nbsp; &nbsp; &nbsp; map[el].value.push([el]);&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; map[el].value[map[el].value.length - 1].push(el);&nbsp; &nbsp; &nbsp; map[el].ind += 1;&nbsp; &nbsp; }&nbsp; } else {&nbsp; &nbsp; map[el] = {&nbsp; &nbsp; &nbsp; value: [[el]],&nbsp; &nbsp; &nbsp; ind&nbsp; &nbsp; }&nbsp; }})for (let k in map) {&nbsp; result.push(map[k].value)}// result就是要的结果

繁花如伊

arr.reduce((a,b)=>(a.arr[b] = a.arr[b] || [], a.arr[b][a.arr[b].length-(a.last === b ? 1 : 0)] = [...(a.arr[b][a.arr[b].length-(a.last === b ? 1 : 0)]||[]), b], a.last = b, a), {last: -1, arr: []}).arr.slice(1)只遍历一次数组如果当前数等于上一个,则结果数组的最后一个子数组更新,否则则对应数组项添加新数组。要求数字必须是大于-1的整数才行。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript