2011-05-12 141 views
0

我有逗號分隔值的像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矩陣並進行轉置。

+7

讓我們看看你的一些嘗試! – Patricia 2011-05-12 12:19:28

+0

你想把它當作一個3x3矩陣來做一個轉置嗎? – 2011-05-12 13:25:36

+0

@Adam Bergmark:確切地說,任何建議,即時嘗試很長一段時間 – kiran 2011-05-12 13:44:05

回答

4

array.slice將是我的建議

在你的具體情況來看看這個

<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> 
+0

即時通訊有一個昏迷的價值數組A = 0,1,0,1,0,0,0,0,1我想基於它transporse它on count如果它的3我螞蟻兩個數組像B = 0,1,0 c = 1,0,0 d = 0,0,1 - 需要一個transporse – kiran 2011-05-12 13:16:42

+0

@Kiran請參閱更新 - 也許你正在尋找實際的轉置: http://www.shamasis.net/2010/02/transpose-an-array-in-javascript-and-jquery/ – mplungjan 2011-05-12 14:57:21

2

嘗試array.slice(start, end)

例子: -

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

樂趣! 你唯一需要知道的是轉置,在矩陣中設置m(i,j)= m(j,i)forall(i,j)。我最終轉換爲一個矩陣表示,它不那麼簡潔,但是mor清晰可辨...

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)))));