开发者

splitting an array

I have an array of comma separated values like var myArray = [0,1,0,1,0,0,0,0,1]

I want to split it based on a count if count is 3 I want to end up with three arrays like

var myArrayA = [0,1,0];
var myArrayB = [1,0,0];
var myArrayC = [0,0,1];  

I need to treat it as a 3x3 matrix and do开发者_开发技巧 a transpose.


array.slice would be my suggestion

in your SPECIFIC situation have a look at this

<script>
function getMatrix(arr,count) {
  var res = {};
  for (var i=0;i<arr.length;i+=count) {
    res[i]=arr.slice(i,(i+count));
  }
  return res;
}
var result = getMatrix("0,1,0,1,0,0,0,0,1".split(","),3);
for (var o in result) alert(result[o]);
</script>


Try array.slice(start, end)

Example:-

var firstArray = array.slice(0,count);
var secondArray = array.slice(count);


Fun! The only thing you need to know really is that to transpose, set m(i,j) = m(j,i) forall (i,j) in the matrix. I ended up converting to a matrix representation, which is less concise but mor legible...

var a = [1,2,3,4,5,6];
function listToSquareMatrix(a,colDim) {
  a = a.slice(0);
  var res = [];
  var row = 0;
  var col;
  for(; a.length; row++) {
    for(col = 0; col < colDim; col++) {
      res.push({
        row : row,
        col : col,
        val : a.shift()
      });
    }
  }
  return res;
}
function transpose(m) {
  for(var i=0; i < m.length; i++) {
    var v = m[i];
    var row = v.row;
    v.row = v.col;
    v.col = row;
  }
  return m.sort(function (a,b) { var r = compare(a.row,b.row); var c = compare(a.col,b.col); return r !== 0 ? r : c });
}
function compare(a,b) {
  if (a < b) {
    return -1;
  } else if (b < a) {
    return 1;
  }
  return 0;
}
function matrixToArray(m) {
  var res = [];
  for (var i = 0; i < m.length; i++) {
    res.push(m[i].val);
  }
  return res;
}
console.log(listToSquareMatrix(a, 3));
console.log(matrixToArray(transpose(listToSquareMatrix(a, 3))));
console.log(matrixToArray(transpose(transpose(listToSquareMatrix(a, 3)))));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜