'sort .map data in react js (show latest date on top)
I am trying to sort data according to date where the latest date must come at top of the list
let mapped = predefined.reduce((r, a) => {
r[a.date] = [...(r[a.date] || []), a];
return r;
}, {});
I tried mapping like this
mapped has the list of data but when I call the item.date nothing is printing
{Object.values(mapped).map((item, index) => (
<tr style={styles.tr}>
<td>{item.date}</td>
<td>
{item.criticality == "high risk" ? (
<button
// onClick={() => findgraph(user.id)}
style={styles.red}
></button>
) : item.criticality == "stable" ? (
<button
// onClick={() => findgraph(user.id)}
style={styles.green}
></button>
) : (
<button
// onClick={() => findgraph(user.id)}
style={styles.yellow}
></button>
)}
</td>
<td>
<button>view</button>
</td>
</tr>
))}
code sandbox with data
Solution 1:[1]
The DD-MM-YYYY format is not identified by new Date() and returned Invalid Date as it checks the DD place for a month and when DD is greater than 12 it fails. Had to use a simple util function to do the string to date conversion.
Try like below.
Util function to convert date properly.
const getDateObjectFromString = (dateString) => {
const [day, month, year] = dateString.split("-");
return new Date(year, month - 1, day, 0, 0, 0, 0);
};
In your useEffect to load the data do sort and set the values.
const predefinedData = res.data;
predefinedData.sort(({ date: firstDate }, { date: secondDate }) => {
return (
getDateObjectFromString(secondDate) -
getDateObjectFromString(firstDate)
);
});
setpredefined(predefinedData);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Amila Senadheera |
