表中的反向排序

时间:2017-08-17 09:43:54

标签: javascript reactjs

我已经有了逐渐id呈现表格行的函数。如何反转它? (第一行id=n,最后一行1)

这就是我的代码

renderRows = () => {
    const { receipts } = this.props
    const rows = receipts.map((receipt, index) => (
      <tr key={index}>
        <td>{receipt.id}</td>
        <td >{receipt.organization.name}</td>
        <td>{receipt.receiptNumber}</td>
        <td>{receipt.series}</td>
        <td>{receipt.customer.fname}</td>
        <td>{receipt.customer.lname}</td>
        <td>{receipt.customer.patronymic}</td>
        <td>{receipt.customer.phone}</td>
        <td>
          {receipt.priceList.map((priceListEntry, index) =>
            <div key={index}>
              {priceListEntry.service.name}
            </div>
          )}
        </td>
     </tr>);
   return (rows);
 }

3 个答案:

答案 0 :(得分:1)

您可以执行const rows = receipts.reverse().map(/*[...]*/)

Reverse Documentation

您还可以使用sort()功能创建所需的确切订单。 (此处:const rows = receipts.sort((a,b) => { return b.id - a.id}).map(/*[...]*/)

答案 1 :(得分:1)

您可以根据receipts ID使用Array#Sort

renderRows = () => {
    const { receipts } = this.props
    receipts.sort((a, b) => b.id - a.id);
    const rows = receipts.map((receipt, index) => (
      <tr key={index}>
        <td>{receipt.id}</td>
        <td >{receipt.organization.name}</td>
        <td>{receipt.receiptNumber}</td>
        <td>{receipt.series}</td>
        <td>{receipt.customer.fname}</td>
        <td>{receipt.customer.lname}</td>
        <td>{receipt.customer.patronymic}</td>
        <td>{receipt.customer.phone}</td>
        <td>
          {receipt.priceList.map((priceListEntry, index) =>
            <div key={index}>
              {priceListEntry.service.name}
            </div>
          )}
        </td>
     </tr>);
   return (rows);
 }

答案 2 :(得分:1)

您可以使用javascript sort功能: DOC

renderRows = () => {
    let receipts = this.props.receipts
    receipts.sort(function(a,b){ return b.id - a.id})
    const rows = receipts.map((receipt, index) => (
      <tr key={index}>
        <td>{receipt.id}</td>
        <td >{receipt.organization.name}</td>
        <td>{receipt.receiptNumber}</td>
        <td>{receipt.series}</td>
        <td>{receipt.customer.fname}</td>
        <td>{receipt.customer.lname}</td>
        <td>{receipt.customer.patronymic}</td>
        <td>{receipt.customer.phone}</td>
        <td>
          {receipt.priceList.map((priceListEntry, index) =>
            <div key={index}>
              {priceListEntry.service.name}
            </div>
          )}
        </td>
     </tr>);
   return (rows);
 }
相关问题