数组算法问题求解

遇到一个算法;类似 var a= [1,2,3,4,4 ,5,5,5] 怎么处理成二位数组[[1],[2],[4,4],[5,5,5]]

我自己写的:额。。。循环两次,不太好


var a= [1,2,3,4,4,5,5,5];

    var obj = {};

    var arr = [];

    for(var i = 0; i<a.length; i++) {

        if(!obj[a[i]]){

            obj[a[i]] = [];

        }

        obj[a[i]].push(a[i]);

    }

    for(var i in obj){

        arr.push(obj[i]);

    }

    console.log(arr);


慕码人2483693
浏览 421回答 3
3回答

一只名叫tom的猫

排序后 一遍循环就行let a= [1,2,3,4,4,5,5,5];let a2 = []for(let i=0;i<a.length;i++){&nbsp; &nbsp; if(i==0||a[i]!=a[i-1]){&nbsp; &nbsp; &nbsp; &nbsp; a2.push([])&nbsp; &nbsp; }&nbsp; &nbsp; a2[a2.length-1].push(a[i])}

qq_花开花谢_0

var arr = [1,2,3,4,4 ,5,5,5]var ret = []var prev = [arr[0]]for (let i = 1; i < arr.length; i++) {&nbsp; if (arr[i] === prev[0]) {&nbsp; &nbsp; prev.push(arr[i])&nbsp; } else {&nbsp; &nbsp; ret.push(prev)&nbsp; &nbsp; prev = [arr[i]]&nbsp; }}ret.push(prev)

慕沐林林

test = [1,2,3,4,4,5,5,5]res = dict()for i in test:&nbsp; if not res.has_key(i):&nbsp; &nbsp; res[i] = []&nbsp; res[i].append(i)print res.values()
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript