Reputation: 253
I have an array of objects. Each object has a date property. I am trying to create a function where I append every item to a new array if the item's date is equal to today's date.
Also, I am not sure if the for loop is the most efficient approach for this, this list will never be more than a few hundred items though.
My function:
todayListItems() {
const todayItems = [];
const todayDate = moment(new Date()).format('dd-mm-YYYY');
for (let i = 0; i < myArray.length; i++) {
const itemDate = moment(myArray[i].date).format('dd-mm-YYYY');
if (itemDate === todayDate) {
todayItems.push(myArray[i]);
}
}
console.log(todayItems);
return todayItems;
}
This function runs but even if there is an item with today's date nothing will be pushed to the array.
Upvotes: 1
Views: 1007
Reputation: 12984
You can use Array.filter()
and moment#isSame
with the second parameter to limit the granularity to a unit other than milliseconds:
function todayListItems(arr) {
return arr.filter(obj => moment().isSame(obj.date, 'day'));
}
todayListItems(myArray);
Demo:
function todayListItems(arr) {
return arr.filter(obj => moment().isSame(obj.date, 'day'));
}
const myArray = [
{ date: '2019-10-14T12:10:00Z'},
{ date: new Date() },
{ date: moment().minutes(120).format('YYYY-MM-DDTHH:mm:ss') },
{ date: new Date('2019-10-23T01:00:00') },
];
console.log(todayListItems(myArray));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
Upvotes: 1
Reputation: 752
You're formatting wrongly. mm
is minutes. The formatting should be DD-MM-YYYY
, see https://momentjs.com/docs/#/displaying/format/
Upvotes: 1