1

If I have an array of arrays as follows:

[ [ A0 , B0 , C0 , D0 , E0 ],
  [ A1 , B1 , C1 , D1 , E1 ],
  [ A2 , B2 , C2 , D2 , E2 ]  ] // array of 3x5

and I want to get a new array of subset arrays like so:

[ [ A0 , B0 , C0           ],
  [      B1 , C1 , D1      ],
  [           C2 , D2 , E2 ]  ]  //array of 3x3

This means that the sliceLength = 3, but how can one do this? Is it better to use splice (as in duplicate the original, then remove the unwanted parts), slice, and/or push?

This is what I have thus far, but the syntax looks off:

var newMega = [];
var sliceLength = 3;
for (var i=0; i<originalMatrix.length; i++) {
  var inner = originalMatrix.slice(i, sliceLength);  //  Here is the issue
  newMega.push(inner); 
}

It appears that the syntax would call slice on the entire originalMatrix, without knowing which index of the nested arrays it should be slicing. Should it be originalMatrix[i].slice(i, sliceLength)?

4
  • I don't think .slice is the correct method to use here. It looks like you want to end up with 3 arrays of length 5, but without values at some positions. .slice will always return an array of length three in your case. It looks like you have to delete the elements that you don't want. This will preserve the length (5) of each inner array. Commented Nov 18, 2013 at 16:41
  • 1
    Do you want to end up with arrays if length 3 or length 5? edit: Ok :) Your example looks a bit like you wanted a sparse matrix. Commented Nov 18, 2013 at 16:46
  • 1
    @FelixKling sorry for this misconception, 3x3 Commented Nov 18, 2013 at 16:47
  • 1
    @FelixKling Well, you just cost me another 10 minutes looking into what a sparse array is! Thanks, learning a lot. Commented Nov 18, 2013 at 16:57

1 Answer 1

2

Try slicing the inner array (originalMatrix[i]). Also, you probably want to call splice rather than slice:

var newMega = [];
var spliceLength = 3;
for (var i=0; i<originalMatrix.length; i++) {
  var inner = originalMatrix[i].splice(i, spliceLength);
  newMega.push(inner); 
}

Here's a demonstration.

Sign up to request clarification or add additional context in comments.

3 Comments

This would result in each of the inner arrays have a length of three. Based on the OP's example I don't think that's what they want, but I could be just misinterpreting the example.
@FelixKling That's exactly the way I read the question. Each sub-array has length 3.
I read it that each arrays should still have length 5, but has "holes" at some positions. Anyways, the OP clarified and your interpretation is correct.

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.