1

I have an array of arrays with none of the elements having names that is being generated. Each sub-array will have the same number of elements but the total number of sub-arrays is variable. For example,

var arrayAll = [
    [a,b,c,d,e,f],
    [g,h,i,j,k,l],
    [m,n,o,p,q,r]
];

I'd like to be able to access one element out of one array, i.e. just 'j', but am not sure of any notations to do it as I only have numbers. I've seen a few ways to access nested arrays but they all rely on the array having named items which I don't have.

AQShedim
  • 23
  • 3

3 Answers3

1

You can easily access the items by number as if it were a multi-dimensional array:

var row = 2, // 3rd row - JS arrays are 0-indexed
    item = 3, // 4th item
    x = arrayAll[row][item];

alert(x); // "p"
David Millar
  • 1,858
  • 1
  • 14
  • 23
1

I guess what he is looking for is a way of accessing the same column in every row. It can be done with the map function:

var arrayAll = [
    [a,b,c,d,e,f],
    [g,h,i,j,k,l],
    [m,n,o,p,q,r]
];

var oneColumn = arrayAll.map(function(row){ return row[3]});

// oneColumn = [d, j, p];
Christian Landgren
  • 13,127
  • 6
  • 35
  • 31
0

You can do it dynamically at any depth, given a path as an array, and using a reducer:

var searchByPath = function(path, xs) {
  return path.reduce(function(acc, k) {
    return acc && acc[k]
  },xs)
}

For example:

var xs = [
  [1,2,3,4],
  [5,6,7,8]
]

// xs[1][2]
searchByPath([1,2], xs) //=> 7

// xs[3][100]
searchByPath([3,100], xs) //=> undefined
elclanrs
  • 92,861
  • 21
  • 134
  • 171