Issue
This Content is from Stack Overflow. Question asked by Calvin Care
I wanted to list all users who are having birthday in current month in an ascending order.
const user = [
{
name: 'xxx',
dob: '21-09-1988'
},
{
name: 'yyy',
dob: '30-09-2000'
},
{
name: 'zzz',
dob: '01-10-1988'
},
]
Below is my code
const today = new Date();
this.members.forEach((member) => {
let birthdate = member.dob.split('-')[0];
let birthmonth = member.dob.split('-')[1];
console.log(birthmonth);
if (birthmonth === today.getMonth()+1) {
this.birthdayMembers.push(member);
}
});
Please help to resolve this.
Solution
You need to loop users array, compare months, push users to resulting array and then sort it as you need. Obviously this is just one of many ways to solve this. Check inline comments:
// Users
const users = [
{
name: 'yyy',
dob: '30-09-2000'
},
{
name: 'xxx',
dob: '21-09-1988'
},
{
name: 'zzz',
dob: '01-10-1988'
}
];
// Get current month
const cm = new Date().getMonth()+1;
// Loop users and compare months
// If month match, push user to filtered array
const fa = [];
for(const u of users) if(cm == u.dob.split("-")[1]) fa.push(u);
// Then sort your array as you wish (i.e ASC)
fa.sort((a, b) => (a.dob > b.dob ? 1 : -1));
// Test result
console.log(fa);
This Question was asked in StackOverflow by Calvin Care and Answered by tarkh It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.