简体   繁体   中英

One dimensional to two dimensional array javascript

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) );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM