admin管理员组文章数量:1352250
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 pletely different operator in Javascript.
Thanks
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 pletely different operator in Javascript.
Thanks
Share Improve this question asked Jul 2, 2013 at 8:54 JanJan 1252 silver badges5 bronze badges 2- you can always just offset from the first column, why won't that work? – epoch Commented Jul 2, 2013 at 9:00
-
@epoch How would you go about offseting from the first column? Assuning you had an array of the form
myArray = [[1,2,3],[4,5,6],[7,8,9]]
– Jan Commented Jul 2, 2013 at 9:11
2 Answers
Reset to default 6If 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]]
本文标签: How do I subset a 2dimensional array in JavascriptStack Overflow
版权声明:本文标题:How do I subset a 2-dimensional array in Javascript? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1743636189a2513938.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论