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

Time:06-02

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

CodePudding user response:

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()));
})
  • Related