Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Multidimensional arrays - column to row

Is it possible to turn a column of a multidimensional array to row using JavaScript (maybe Jquery)? (without looping through it)

so in the example below:

 var data = new Array();

 //data is a 2D array
 data.push([name1,id1,major1]);
 data.push([name2,id2,major2]);
 data.push([name3,id3,major3]);
 //etc..

Is possible to get a list of IDs from data without looping? thanks

like image 234
sarsnake Avatar asked Dec 05 '22 00:12

sarsnake


1 Answers

No, it is not possible to construct an array of IDs without looping.

In case you were wondering, you'd do it like this:

var ids = [];
for(var i = 0; i < data.length; i++) 
    ids.push(data[i][1]);

For better structural integrity, I'd suggest using an array of objects, like so:

data.push({"name": name1, "id": id1, "major":major1});
data.push({"name": name2, "id": id2, "major":major2});
data.push({"name": name3, "id": id3, "major":major3});

Then iterate through it like so:

var ids = [];
for(var i = 0; i < data.length; i++) 
    ids.push(data[i].id);
like image 175
Jacob Relkin Avatar answered Dec 08 '22 14:12

Jacob Relkin