我有一组逗号分隔值,例如var myArray = [0,1,0,1,0,0,0,0,1]
如果计数为3,我想根据计数拆分它我希望最终得到三个数组,如
var myArrayA = [0,1,0];
var myArrayB = [1,0,0];
var myArrayC = [0,0,1];
我需要将其视为3x3矩阵并进行转置。
答案 0 :(得分:4)
array.slice将是我的建议
在您的SPECIFIC情况下看看这个
<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>
答案 1 :(得分:2)
尝试array.slice(start, end)
实施例: -
var firstArray = array.slice(0,count);
var secondArray = array.slice(count);
答案 2 :(得分:0)
趣味! 你唯一需要知道的是转置,在矩阵中设置m(i,j)= m(j,i)forall(i,j)。我最终转换为矩阵表示,这种表示不那么简洁但是很清晰......
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)))));