7

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

2
  • you can always just offset from the first column, why won't that work? 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]] Commented Jul 2, 2013 at 9:11

2 Answers 2

6

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);
Sign up to request clarification or add additional context in comments.

8 Comments

From what I understand that returns an array of the first elements of each of the original arrays.
Mmm, I'm not sure I understand your question but if you have a = [[1,2],[1,2],[1,2]] it will return [2,2,2].
Ah yes, you're correct, I'm used to 1-indexed languages. However that still does not solve my problem, say I had myArray = [[1,2,3],[4,5,6],[7,8,9]] and wanted to retrieve [[2,3],[5,6],[8,9]]
Then you can return those columns: return [v[1],v[2]]
Alright, I guess I'll just have to do that, I was hoping there would be a cleaner method as I am working with a slightly larger array.
|
6

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

Comments

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.