Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get column from a two dimensional array

Tags:

javascript

How can I retrieve a column from a 2-dimensional array and not a single entry? I'm doing this because I want to search for a string in one of the columns only so if there is another way to accomplish this please tell me.

I'm using the array defined this way:

var array=[]; 

At the end the size of this array is 20(col)x3(rows) and I need to read the first row and check the existence of some phrase in it.

like image 279
Ameen Avatar asked Oct 21 '11 10:10

Ameen


1 Answers

Taking a column is easy with the map function.

// a two-dimensional array var two_d = [[1,2,3],[4,5,6],[7,8,9]];  // take the third column var col3 = two_d.map(function(value,index) { return value[2]; }); 

Why bother with the slice at all? Just filter the matrix to find the rows of interest.

var interesting = two_d.filter(function(value,index) {return value[1]==5;}); // interesting is now [[4,5,6]] 

Sadly, filter and map are not natively available on IE9 and lower. The MDN documentation provides implementations for browsers without native support.

like image 168
Leif Carlsen Avatar answered Oct 21 '22 21:10

Leif Carlsen