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)
?
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 .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.