Search code examples
htmlhtml-tablecreateelement

Inserting last data object into first table row - HTML


The following data:

[
  { address: '101 Main Street', date_created: '2022/11/01', price: '£100,000' },
  { address: '101 Main Street', date_created: '2022/10/27', price: '£200,000' },
  { address: '101 Main Street', date_created: '2022/10/20', price: '300,000' },
];

is passed to my createTable function:

function createTable({ data, propertyId }) {
  const table = createElement({
    tag: 'table',
    id: `p-${propertyId}`,
    border: '1',
  });

  const tableHeader = createElement({
    tag: 'caption',
    innerText: 'Table title',
  });

  const tableBody = createElement({
    tag: 'tbody',
  });

  data.forEach((item) => {
    const row = createElement({
      tag: 'tr',
    });

    const date = createElement({
      tag: 'td',
      innerHTML: item.date_created,
    });

    const price = createElement({
      tag: 'td',
      innerHTML: item.price,
    });

    row.append(date, price);
    tableBody.append(row);
  });

  table.append(tableHeader, tableBody);
  return table;
}

which creates the following output:

2022/11/01 £100,000
2022/10/27 £200,000
2022/10/20 £300,000

This means that the first object is inserted into the first row and so on, however, I'd like to display the data in the opposite order. (Oldest data at the top, with newest at the bottom) - number of records can vary.


Solution

  • function createTable({ data, propertyId }) {
        const table = createElement({
            tag: "table",
            id: `p-${propertyId}`,
            border: "1"
        });
    
        const tableHeader = createElement({
            tag: "caption",
            innerText: "Table title"
        });
    
        const tableBody = createElement({
            tag: "tbody"
        });
    
        // the change is here,  hope it helps
        data.sort((prev, current) => {
            const prevDate = prev["date_created"]
                .replace("/", "-")
                .replace("/", "-");
            const currentDate = current["date_created"]
                .replace("/", "-")
                .replace("/", "-");
            return new Date(prevDate) - new Date(currentDate);
        }).forEach(item => {
            const row = createElement({
                tag: "tr"
            });
    
            const date = createElement({
                tag: "td",
                innerHTML: item.date_created
            });
    
            const price = createElement({
                tag: "td",
                innerHTML: item.price
            });
    
            row.append(date, price);
            tableBody.append(row);
        });
    
        table.append(tableHeader, tableBody);
        return table;
    }