How to reverse array, or map with descending order?
<tbody>
{Array(10).fill(1).map((el, i) =>
<ObjectRow key={i} />
)}
</tbody>
reverse
function does not work
<tbody>
{Array(10).fill(1).reverse().map((el, i) =>
<ObjectRow key={i} />
)}
</tbody>
CodePudding user response:
You have 2 mistakes here.
First you load an array with 1s, which means that you have identical elements inside your array, so reverse
is pointless.
Second you use the index
as a key
inside your map
method and not the actual reversed element (using index
as key
is not considered best practice).
The correct way should be
<tbody>
{ [...Array(10).keys()].reverse().map((el, i) =>
<ObjectRow key={el} />
)}
</tbody>