bopjesvla
bopjesvla

Reputation: 763

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?

Upvotes: 1

Views: 4554

Answers (2)

Mike Thomsen
Mike Thomsen

Reputation: 37524

Something like this, perhaps:

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

Upvotes: 1

Van Coding
Van Coding

Reputation: 24554

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

Upvotes: 2

Related Questions