Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I subset a 2-dimensional array in Javascript?

I have been looking around, and seen that it is possible to retrieve an element from a two dimensional array with something like myArray[x][y]. However what I am looking to do take everything but the first column.

In R one would just use myArray[x,2:y] however I am aware that the colon is a completely different operator in Javascript.

Thanks

like image 784
Jan Avatar asked Jul 02 '13 08:07

Jan


2 Answers

If you want to take everything in y try map:

var y = myArray.map(function(v){ return v[1] });

Not sure if this is the equivalent of the R you posted...

If you want to subtract the first column try like:

return v.slice(1);
like image 177
elclanrs Avatar answered Sep 21 '22 11:09

elclanrs


Your example where you had myArray = [[1,2,3],[4,5,6],[7,8,9]] and wanted to retrieve [[2,3],[5,6],[8,9]]

you could do something like this:

var myArray = [[1,2,3],[4,5,6],[7,8,9]];    
var results = [];

for(var i = 0; i < myArray.length; i++){
  results.push(myArray[i].slice(1,3));
}
//results === [[2,3],[5,6],[8,9]];

If you want to slice the indexes after index[0] from each sub-array, then you might want to go with this approach instead:

var myArray = [[1,2,3],[4,5,6],[7,8,9]];    

var sliceSubset = function(array){
  var results = [];
  for(var i = 0; i < array.length; i++){
    results.push(array[i].slice(1,array[i].length));
  }
  return results;
}

sliceSubset(myArray); //returns [[2,3],[5,6],[8,9]]
//works on different sized arrays as well
var myOtherArray = [[1,2,3,9],[4,5,6],[7,8,9]];
sliceSubset(myOtherArray); //returns [[2,3,9],[5,6],[8,9]]
like image 38
Tyler Davis Avatar answered Sep 18 '22 11:09

Tyler Davis