Reputation: 7741
I would like to render an array in Svelte with the following form with two nested each loops.
const arr = [
[ a, b, c ],
[ d, e, f ],
[ g, h, i ]
]
{#each arr as row, rowIndex}
<div class="row">
{#each row as cell, cellIndex ($arr[rowIndex][cellIndex]) }
<div class="cell"> {cell} </div>
{/each}
</div>
{/each}
Demo REPL -> https://svelte.dev/repl/4dbec2d8c2ac4b6493e78418bd861f4c?version=3.38.2
Wanted effect => clicked element vanishes first, then elements to the right move over
When setting {#each arr as row, rowIndex (rowIndex)}
+ {#each row as cell, cellIndex (cellIndex)}
it doesn't behave like that (-> https://svelte.dev/repl/e7369788e2614bbbbf9c42cde6a4130a?version=3.38.2)
In case the content of each cell is unique, setting the id on the cell like this works fine ->
($arr[rowIndex][cellIndex])
But if two cells contain the same content, that's not working. (Activate last element in arr in REPL store -> 'Cannot have duplicate keys in a keyed each')
So I am wondering if there is any way to set a unique id in this case on a different way?
I came up with some approaches to combine the rowIndex with the cellIndex e.g. like '00, 01, 02, 10, 11, 12, 20, ...' but nothing of these worked:
rowIndex.toString().concat(cellIndex.toString())
""+rowIndex+cellIndex
+(""+rowIndex+cellIndex)
$arr[rowIndex][cellIndex]+rowIndex+cellIndex
Upvotes: 0
Views: 1854
Reputation: 1260
Why not use cellIndex
as key in the inner #each
instead of $arr[rowIndex][cellIndex]
? This works because the key only needs to be unique within one particular #each
which every nested #each
ends up being.
Upvotes: -1