Reputation:
I have an array of objects which includes the date element. I want to find the latest 10 dates from the element and render them inside a table. Rendering inside a mapping of each data
with data.date
, I get this:
2020-12-12
2020-04-27
2020-08-26
2020-05-09
...
2020-09-08
2020-06-23
2020-02-28
2020-04-01
Data also have different properties like id
, customer_id
, customer_name
and an array of invoices
. I want to find the 10 latest dates and show the customer name for the invoice, among other properties.
const findLatestDates = () => {
const sortedArray = data.sort((a,b) => new Moment(a).format('YYYYMMDD') - new Moment(b).format('YYYYMMDD'))
return sortedArray;
};
I am thinking of sorting the date by array and loop through 15 times to show it on render. Is this a good idea? Also, there is a problem getting raised on new Moment
'new' expression, whose target lacks a construct signature, implicitly has an 'any' type.ts(7009)
Upvotes: 0
Views: 361
Reputation: 1927
Using Moment for this seems to be a bit overkill, I'd try sorting it using the native Date
constructor:
const findLatestDates = (data) => {
// Sort all data by date in a descending order
const sortedArray = data.sort(
(a, b) => new Date(b.date).getTime() - new Date(a.date).getTime()
);
// Get each data point corresponding to the most recent 10 days
const latestData = sortedArray.slice(0, 10);
return latestData;
};
If you run this function on the original array of data you have, each of your items should still be together and you can render them as you want. There should be no need to loop through the data 15 times to get the data you need.
Upvotes: 1