簡體   English   中英

如何在 javascript 中將坐標轉換為二維數組

[英]How can I turn coordinates to two dimensional array in javascript

在我的項目中,我必須將一堆坐標轉換為一些有意義的二維數組,但我真的不知道該怎么做。 有人可以幫忙嗎?

為了解釋我到底想要什么,讓我舉個例子:

假設我有這兩個數組(我從一個開始的原因是因為 0 和我的行的最后一個元素是邊框):

[[1, 1], [1, 2], [1, 4], [1, 5], [1, 8], [1, 9], [1, 10],[2, 1], [2, 2], [2, 4], [2, 5], [2, 6], [2, 7], [2, 8], [2, 10]] 

讓這些坐標內的值類似於 [row,col]。 假設我不想匹配它們來生成某種二維數組,並且每個元素都應該包含值“#”。 但是,例如;

[1, 2], [1, 4]
[2, 2], [2, 4]

如果其中兩個元素之間缺少坐標,則應該將它們分開,這意味着應該有兩個不同的二維 arrays,從該坐標中分割出來。 在這種情況下,結果應該是;

// First two-dimensional array
const firstArray = [
['#','#'],
['#','#']
]
const secondArray = [
['#','#','','','#','#','#'],
['#','#','#','#','#','','#'],
]

在第二個數組中,有一些 '' 值,但那是因為缺少一些坐標(對於 [1, 5] 和 [1, 8],缺少 [1,6] 和 [1,7]) . 所以這也應該考慮。

如果您不明白,請在我的問題下發表評論,以便我向您解釋。

我怎樣才能想出我正在尋找的功能?

您可以使用單個Array#reduce()調用來完成這兩個步驟,方法是使用坐標本身將每個[row, col]放置在矩陣中的相關位置。

這里使用OR 短路來分配新的子數組,使用邏輯空賦值運算符 (??=)進行注釋替換,並在箭頭 function中使用逗號運算符進行速記返回。

 const coords = [[1, 1], [1, 2], [1, 4], [1, 5], [1, 8], [1, 9], [1, 10], [2, 1], [2, 2], [2, 4], [2, 5], [2, 6], [2, 7], [2, 8], [2, 10]]; const matrix = coords.reduce((acc, [row, col]) => ( // using OR short circuit for compatibility (acc[row - 1] || (acc[row - 1] = []))[col - 1] = [row, col], acc // using logical nullish assignment operator (??=) //(acc[row - 1]??= [])[col - 1] = [row, col], _matrix ), []) // logging for (const row of matrix) { console.log(`[[${row.join('], [')}]]`) }
 .as-console-wrapper { max-height: 100%;important: top; 0; }

 const input = [[1, 1], [1, 2], [1, 4], [1, 5], [1, 8], [1, 9], [1, 10],[2, 1], [2, 2], [2, 4], [2, 5], [2, 6], [2, 7], [2, 8], [2, 10]] const result = input.reduce((acc, [x, y]) => { acc[x - 1]??= [] const previousY = acc[x - 1][acc[x-1].length - 1]; if (previousY) { const delta = y - previousY; if (delta > 1) acc[x-1].push(...Array.from({length: delta - 1})); } acc[x-1].push(y); return acc }, []) console.log('1234567890') console.log( result.map(row => row.map(coor => coor? '#': ' ').join('') ).join('\n'))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM