2016-12-13 153 views
-2

我有一個數組x=[[3,1],[2,2]],我想將它變成x[3][1]=1x[2][2]=1。該代碼還應該適用於更長的數組,如x=[[3,1],[2,12],[3,3]]將二維數組轉換爲一個稀疏數組陣列

+1

你的術語是錯誤的。 'x = [[3,1],[2,2]] * *是一個二維數組。你要求的是將一個數組數組轉換爲一個稀疏的數組數組。 –

+0

「數組陣列」是一個二維數組 –

+0

仍然可以將[[3,1],[2,2]]轉換爲x [3] [1]和x [2] [2] –

回答

0

您可以迭代並創建一個新數組(如果尚未)。然後將該值分配給給定的索引。

該解決方案需要一個新的數組作爲結果。

var x = [[3, 1], [2, 12], [3, 3]], 
 
    result = []; 
 

 
x.forEach(function (a) { 
 
    result[a[0]] = result[a[0]] || []; 
 
    result[a[0]][a[1]] = 1; 
 
}); 
 

 
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

1

假設你把兩個輸入:pos0pos1

for (i in x) 
    if (x[i][0] == pos0 && x[i][1] == pos1) { 
     // Do stuff 
    } 

所以它基本上是檢查每個指標

0

你可以做如下:

var x = [[3,1],[2,12],[3,3]], 
 
    r = x.reduce((p,c) => (p[c[0]] ? p[c[0]][c[1]] = 1 
 
            : p[c[0]] = Array.from({[c[1]]: 1, length: c[1]+1}), 
 
          p),[]); 
 
console.log(r);

0
const x = [[3,1], [2,2]] 

console.log('x =', x) 

// Initialize 1st dimension array 
const y = [] 
for (let i in x) { 
    // Initialize the 2nd dimension array if not exist 
    y[x[i][0]] = y[x[i][0]] || [] 
    // Assign the value to the sparse array 
    y[x[i][0]][x[i][1]] = 1 
} 

console.log('y =', y) 

輸出:

x = [ [ 3, 1 ], [ 2, 2 ] ] 
y = [ , , [ , , 1 ], [ , 1 ] ] 
0

您可以使用array#reduce通過您的數組進行迭代,並檢查數組存在對應的第一個值,如果它沒有初始化與[],然後將該值分配給該索引。

var x=[[3,1],[2,12],[3,3]]; 
 
var result = x.reduce((r,[a,b]) => { 
 
    r[a] = r[a] || []; 
 
    r[a][b] = 1; 
 
    return r; 
 
},[]); 
 
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }