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
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);
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]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With