1

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];
};
3
  • So... You want to return columns? Those are not nested arrays in your second example, so you will need to iterate through. Commented Mar 20, 2015 at 15:45
  • 1
    You can simplify the loop body to aTemp[i] = [aTest[i][0]];. Also, this will be pretty short with ES6: var aTemp = aTest.map(x => [x[0]]);. Commented Mar 20, 2015 at 15:50
  • @FelixKling those are good shortcuts. Thanks for the tips. Commented Mar 20, 2015 at 15:58

2 Answers 2

2

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];
});

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the answer. Dang, I was hoping to achieve this without looping of some sort. Oh well. Thanks again!
2

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']

1 Comment

Thanks for the complement, I was lazy to go that far ;)

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.