0

I'm calculating the day of the week from the API and I need to replace the last element, which will be today's day to string "Today" in an array.

For example:

I have an array todayCal=[tue, wed, thu, fri, sat, sun, mon] where mon is current date's day and I've to replace that mon with 'Today' while displaying.

my code:

 var weekdays = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
 var d = new Date();
 var day = d.getDay();
 var dayCal = weekdays[day];
 if(dayCal){
     console.log(dayCal[6],'weekday[6]');
     dayCal[6] = 'Today';
 }
 else {
     dayCal= weekdays[day];
 }

Here the last element sat is replaced with 'Today' where as I need current day to replace with 'Today'

3
  • 1
    dayCal is the day string (3 letters), so dayCal[6] isn't going to work Commented May 28, 2018 at 6:40
  • yes, that's where I got strucked on printing the lenght I'm getting as 3 . Commented May 28, 2018 at 6:42
  • Do you need to convert weekdays = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']; to something like ['Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun', 'Mon'] along the way? and then to ['Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun', 'Today'] ? Commented May 28, 2018 at 7:08

3 Answers 3

2

You can use getDay() which returns weekday as a number and replace the value in weekdays with Today using the getDay() returned value.

var weekdays = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
weekdays[new Date().getDay()] = 'Today'
console.log(weekdays);

Sign up to request clarification or add additional context in comments.

Comments

0

You can simply override the value of weakdays[] array. When you do d.getDay() it gives you a 1 pass it get the value from weakdays arrays. It is something like weakdays[1] = 'Today'. like following:

var weekdays = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
var d = new Date();
var day = d.getDay();
if(day){
   weekdays[day] = 'Today'
}else{
   console.log(weekdays);
}
console.log(weekdays);

Comments

-1

please find below modified code snippet.

 var weekdays = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
    var d = new Date();
    var day = d.getDay();
    var dayCal = weekdays[day];
    if(dayCal){
    weekdays[day] = 'Today';
    console.log(weekdays);
    }
    else{
    dayCal= weekdays[day];
    console.log(dayCal);
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.