Adam
Adam

Reputation: 3288

Returning nested arrays from multi-dimensional array

Say I have the following 2x2 array:

var aTest = [
    ['test00','test01'],
    ['test10','test11']
]

I can return all of the nested arrays from the first (zero-eth), parent array. i.e.: aTest[0] returns

['test00', 'test01']

However, I can't do the same thing for the nested array without looping. i.e. I would like to do: aTest[][0]:

[['test00'],['test10']]

Am I mistaken? Is there no way to achieve this without loops:

var aTemp = new Array();
for ( var i = 0; i < aTest.length; i++ ) {
    aTemp[i] = new Array();
    aTemp[i][0] = aTest[i][0];
};

Upvotes: 1

Views: 108

Answers (2)

Ethan Brown
Ethan Brown

Reputation: 27282

Just to expand on Bigood's answer (which is where my mind went), you can create a generalized "col" function that returns a column from a multi-dimensional array (note: JavaScript doesn't have multi-dimensional arrays in the mathematical sense of the word; it simply has arrays that can contain other arrays).

function col(a, n) { return a.map(function(x) { return x[n]; }); }

If you want to be really spiffy, you can add it to Array.prototype (Note: some people feel very strongly that you shouldn't modify built-in types. I'm not one of them.):

Object.defineProperty(Array.prototype, 'col', {
    value: function(n) {
        return this.map(function(x) { return x[n]; });
    },
    enumerable: false
});

Then you can use it like this:

aTest.col(0)    // ['test00', 'test10']
aTest.col(1)    // ['test01', 'test11']

Upvotes: 2

Maen
Maen

Reputation: 10698

You're correct, you have to iterate through each element of your array to achieve this.

You can optimize the code using map() function of Array prototype :

var aTest = [
    ['test00','test01'],
    ['test10','test11']
]

var firstItems = aTest.map(function(item){
   return item[0];
});

Upvotes: 2

Related Questions