將二維陣列轉化為 JavaScript 中的陣列稀疏陣列
假設我們有一個像這樣二維陣列 −
const arr = [ [3, 1], [2, 12], [3, 3] ];
我們需要編寫一個 JavaScript 函式,它接收一個這樣的陣列。
然後該函式應建立一個新的二維陣列,該陣列包含所有元素,這些元素初始化為未定義,而不包含輸入陣列中存在的元素索引。
因此,對於輸入陣列,
output[3][1] = 1; output[2][12] = 1; output[3][3] = 1;
而其餘所有元素都應初始化為未定義
因此,最終輸出應如下所示 −
const output = [ undefined, undefined, [ undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, 1 ], [ undefined, 1, undefined, 1 ] ];
示例
程式碼如下 −
const arr = [
[3, 1],
[2, 12],
[3, 3]
];
const map2D = (arr = []) => {
const res = [];
arr.forEach(el => {
res[el[0]] = res[el[0]] || [];
res[el[0]][el[1]] = 1;
});
return res;
};
console.log(map2D(arr));輸出
而控制檯中的輸出將為 −
[ <2 empty items>, [ <12 empty items>, 1 ], [ <1 empty item>, 1, <1 empty item>, 1 ] ]
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP