horizontal to vertical in a javascript array -


i have sample code below;

var myarray= [], myarray2=[]; var l=100; for(j =0; j< 4;j++){     for(i =0; i<4;i++){                myarray.push([l]);        l=l+100;     }     myarray2.push(myarray);     alert(myarray2[j]); } 

the output be

100,200,300,400,500,600,700,800,900,100,1100,1200,1300,1400,1500,1600 

is possible sort values below in array within array?

100, 500, 900, 1300 200, 600, 1000, 1400 300, 700, 1100, 1500 400, 800, 1200, 1600 

i appreciate help....thanks in advance.

this solution convert flat array multidimentional array have described.

javascript

var array = "100,200,300,400,500,600,700,800,900,100,1100,1200,1300,1400,1500,1600".split(","); var grouping = 4; var result = [];  array.foreach(function (element, index) {     var group = index % grouping;     var temp = result[group];      if (!array.isarray(temp)) {         temp = [];     }      temp.push(element);     result[group] = temp; });  console.log(result); 

on jsfiddle

update:

ok, going assume myarray, suggested @bergi, wish convert , not myarray2. based on assumption here modified solution

javascript

var myarray = [],     myarray2 = []; var l = 100; (var j = 0; j < 4; j++) {     (var = 0; < 4; i++) {         myarray.push([l]);         l = l + 100;     }      myarray2.push(myarray); }  var columns = 4; var result = []; var flattened = myarray.tostring().split(","); var length = flattened.length; var rows = math.round(length / columns);  flattened.foreach(function (element, index) {     var group = index % rows;     var temp = result[group];      if (!array.isarray(temp)) {         temp = [];     }      temp.push(element);     result[group] = temp; });  console.log(result); 

on jsfiddle

here alternative flatten method

var flattened = myarray.reduce(function(a, b) {     return a.concat(b); }); 

if don't like

var flattened = myarray.tostring().split(","); 

and interest sake, jsperf on above flatten methods.


Comments

Popular posts from this blog

linux - Does gcc have any options to add version info in ELF binary file? -

android - send complex objects as post php java -

charts - What graph/dashboard product is facebook using in Dashboard: PUE & WUE -