1

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?

2
  • Just for fun in JavaScript 1.6 (maybe jQuery) arr.join().match(/\d+,\d+,\d+,\d+/g).map(function(s) { return s.split(",") } ) Commented May 3, 2011 at 12:46
  • Isn't it a possibility to work with one format? Saves a lot of looping. Commented Jan 10, 2013 at 14:04

2 Answers 2

1

Something like this, perhaps:

var old = [];
for (var index = 0; index < arr.length; index+= 4)
    old.push( arr.slice(index, index + 4) );
Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

This is very slow with big arrays, since every time the array has to be reindexed

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.