I want to display the objects based on the current month and year
This filters the objects based on the month, I need to filter objects based on the year also.
var array = [{
title: "a",
date: "2018-03-29"
}, {
title: "b",
date: "2018-04-13"
}, {
title: "c",
date: "2018-04-12"
}, {
title: "leave",
date: "2018-04-11"
}, {
title: "d",
date: "2018-06-16"
}],
currentMonth = new Date().getMonth() + 1,
events = array.filter(e => {
var [_, month] = e.date.split('-'); // Or, var month = e.date.split('-')[1];
return currentMonth === +month;
});
console.log(events);
Well to filter by year and month, you just need to get the currentYear along with currentMonth, and then get the year and month of the iterated date.
This is how should be your code:
//Get the currentYear and the currentMonth
currentMonth = new Date().getMonth() + 1,
currentYear = new Date().getFullYear(),
//Get the year and month from the iterated date
var [year, month] = e.date.split('-');
//Then filter the dates
events = array.filter(e => {
var [year, month] = e.date.split('-'); // Or, var month = e.date.split('-')[1];
return (currentMonth === +month) && (currentYear == year);
});
Demo:
var array = [{
title: "a",
date: "2018-03-29"
}, {
title: "b",
date: "2018-04-13"
}, {
title: "c",
date: "2018-04-12"
}, {
title: "leave",
date: "2018-04-11"
}, {
title: "d",
date: "2018-06-16"
}],
currentMonth = new Date().getMonth() + 1,
currentYear = new Date().getFullYear(),
events = array.filter(e => {
var [year, month] = e.date.split('-'); // Or, var month = e.date.split('-')[1];
return (currentMonth === +month) && (currentYear == year);
});
console.log(events);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With