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?
asked May 3, 2011 at 10:59
bopjesvla
7634 gold badges15 silver badges23 bronze badges
2 Answers 2
Something like this, perhaps:
var old = [];
for (var index = 0; index < arr.length; index+= 4)
old.push( arr.slice(index, index + 4) );
answered May 3, 2011 at 11:03
Mike Thomsen
37.7k11 gold badges64 silver badges86 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
var newArr = [];
while(arr.length){
newArr.push(arr.splice(0,4));
}
answered May 3, 2011 at 11:04
Van Coding
24.6k25 gold badges94 silver badges138 bronze badges
1 Comment
bopjesvla
This is very slow with big arrays, since every time the array has to be reindexed
Explore related questions
See similar questions with these tags.
lang-js
arr.join().match(/\d+,\d+,\d+,\d+/g).map(function(s) { return s.split(",") } )