I'm having trouble sorting an array and then mapping it (as part of a to do list, I'm trying to sort the tasks in the global state before mapping it to a new array.
My sandbox is here: https://codesandbox.io/s/to-do-list-lloydr-416wm?file=/src/App.js
The place where I'm trying to do the sorting is here (I'm taking the global state of tasks as a prop and then sorting and mapping it to a new array - but only the mapping works, not the sorting):
const Tasks = ({ tasks, onDelete, onToggle }) => {
return (
<>
{tasks
.sort((a, b) =>
new Date(a.selectedDate).getTime() >
new Date(b.selectedDate).getTime()
? 1
: -1
)
.map((task) => (
<Task
key={task.id}
task={task}
onDelete={onDelete}
onToggle={onToggle}
/>
))}
</>
);
};
export default Tasks;
The initial array of tasks is here:
const [tasks, setTasks] = useState([
{
id: 1,
text: "Doctor's appointment",
selectedDate: "05/12/2021",
// CHANGED DATE TO SELECTEDDATE
priority: true
},
{
id: 2,
text: "Meet Lauren for Birthday Dinner",
selectedDate: "27/09/2021",
priority: true
},
{
id: 3,
text: "Take Nugie to vet cos she's stupid",
selectedDate: "28/09/2021",
priority: true
}
]);
Any help is appreciated, thank you!
CodePudding user response:
The date format it expects is MM/dd/yyyy
instead of dd/MM/yyyy
.
Switch your month and day, or initialize it as a date instead of a string with new Date(2021, 29, 27)
(for example).
Edit: I would recommend you to initialize dates with numbers instead of a string. This way you avoid thinking about which locale your string date should be introduced with