Tengo una tabla que obtiene datos de un objeto llamado blockInfo :
<table> <thead> <tr> <th>Timestamp</th> <th>Block #</th> <th>Block Hash</th> <th>Miner</th> <th>Gas used</th> <th>Txs #</th> </tr> </thead> <tbody> {blockInfo.map((block) => < tr > <td >{timeSince(new Date(block.timestamp * 1000))}</td> <td id="blockNumber">{block.number}</td> <td id="blockHash" >{block.hash}</td> <td>{block.miner}</td> <td>{block.gasUsed}</td> <td>{block.transactions.length}</td> </tr> )} </tbody> </table> Quiero ordenar esa tabla por números ascendentes de la columna Block # , intenté agregar .sort() de esta manera pero no funcionó:
<tbody> {blockInfo.sort((a, b) => { if (a > b) return 1; if (a < b) return -10; return 0; }).map((block) => < tr > <td >{timeSince(new Date(block.timestamp * 1000))}</td> <td id="blockNumber">{block.number}</td> <td id="blockHash" >{block.hash}</td> <td>{block.miner}</td> <td>{block.gasUsed}</td> <td>{block.transactions.length}</td> </tr> )} </tbody>¿Alguien cómo puedo hacer eso?
Creo que el error radica en su función de clasificación. Cada uno de los argumentos a y b representa un objeto en la lista blockInfo . Por lo tanto, para que la función de clasificación funcione correctamente, debe especificar la clave en la que desea clasificar.
Prueba este código:
<tbody> {blockInfo.sort((a, b) => { if (a.number > b.number) return 1; // .number is added if (a.number < b.number) return -10; // .number is added return 0; }).map((block) => < tr > <td >{timeSince(new Date(block.timestamp * 1000))}</td> <td id="blockNumber">{block.number}</td> <td id="blockHash" >{block.hash}</td> <td>{block.miner}</td> <td>{block.gasUsed}</td> <td>{block.transactions.length}</td> </tr> )} </tbody>