开发者

One dimensional to two dimensional array javascript

开发者 https://www.devze.com 2023-03-02 02:50 出处:网络
First I have an array like: arr = [[r,g,b,a],[r,g,b,a],[r,g,b,a],[r,g,b,a],[r,g,b,a],[r,g,b,a]] I can \'flatten\' it using

First I have an array like:

arr = [[r,g,b,a],[r,g,b,a],[r,g,b,a],[r,g,b,a],[r,g,b,a],[r,g,b,a]]

I can 'flatten' it using

arr = Array.prototype.concat.apply([],arr)
开发者_运维知识库

or using a for-next loop and push.apply

Then I got:

[r,g,b,a,r,g,b,a,r,g,b,a,r,g,b,a,r,g,b,a]

How do I get it back to its original format as easy as possible?


var newArr = [];
while(arr.length){
    newArr.push(arr.splice(0,4));
}


Something like this, perhaps:

var old = [];
for (var index = 0; index < arr.length; index+= 4)
    old.push( arr.slice(index, index + 4) );
0

精彩评论

暂无评论...
验证码 换一张
取 消