Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to pass an array of strings to Date function in javascript?

I need to get Day’s name from a date. For that, I wrote a function(getDayName) using the date method.

I want to pass the date from a JSON to date method. But I’m getting undefined as a result. What I observed was passing an array of two strings. What I need to do is pass one string at a time to a date method. Here’s my code. Can some one help me out?

//get day name from date

const array = [{
    name: 'Dwayne Langer',
    birthdate: '06-03-2001'
},
{
    name: 'Doffer Henry',
    birthdate: '06-01-2005'
}]

const getBirthDate = array.map(function (birth) {
    return birth.birthdate; 
});
console.log("BirthDate", getBirthDate) 
// BirthDate (2) ['06-03-2001', '06-01-2005']

const dayIndex = new Date(getBirthDate).getDay();
const getDayName = (dayIndex) =>{
    const days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
    return days[dayIndex];
}
const dayName = getDayName(dayIndex)
console.log("Day Name",dayName);
// Day Name undefined

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

the constructor of Date only takes a string as an argument, so what you actually have to do is to loop over the array of people and for each get the birthday for which then get the day of the week.

Here’s my solution:

    //get day name from date

const array = [
  {
    name: 'Dwayne Langer',
    birthdate: '06-03-2001'

  },
  {
    name: 'Doffer Henry',
    birthdate: '06-01-2005'
  }
]

const getBirthDate = (person) => person.birthdate;

const getDayName = (dayIndex) =>{
  const days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
  return days[dayIndex];
}

array.forEach(person => {
    console.log("Day Name", getDayName(new Date(getBirthDate(person)).getDay()));
})
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading