2

What is the best way to convert day name to day position.

I have array:

var days = ['Monday','Sunday','Friday']

How to convert into: newArray = [0,6,4]

I try this:

function getClosedDates() {
         var url = "/getClosedDates"; // the script where you handle the form input.
         var WEEKDAYS = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];
var newArray = [];
var days = [];
  $.ajax({
           type: "GET",
           url: url,
           dataType: "json",
           success: function(data)
           {

 days = data.data.ClosedDays;
newArray = days.map(function(day) {
  return WEEKDAYS.indexOf(day);
});
           }
         });
return newArray;
};

but I get [], empty array... Why?

Aleks Per
  • 1,549
  • 7
  • 33
  • 68
  • 1
    this question was already answered here: https://stackoverflow.com/questions/9677757/how-to-get-the-day-of-the-week-from-the-day-number-in-javascript – capote1789 Jul 13 '17 at 16:24

2 Answers2

6
var WEEKDAYS = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];

var days = ['Monday','Sunday','Friday'];

var newArray = days.map(function(day) {
  return WEEKDAYS.indexOf(day);
})
4castle
  • 32,613
  • 11
  • 69
  • 106
savinger
  • 6,544
  • 9
  • 40
  • 57
  • 1
    @Koushik Please do not edit code beyond fixing formatting or obvious typos. If you would like to change the code, make your own answer, or leave the suggestion in a comment. – 4castle Jul 13 '17 at 16:29
  • 1
    Sure, actually its marked as duplicate. and another point here is using a object as key/value of dayString to number could be faster as the input array may be big, so each time we will be iterating by `.indexOf` – Koushik Chatterjee Jul 13 '17 at 16:33
  • I update my question, please help! – Aleks Per Jul 13 '17 at 16:53
1

Try this:

var days = {'Monday': 0, 'Tuesday': 1, 'Wednesday': 2, 'Thursday': 3, 'Friday': 4, 'Saturday': 5, 'Sunday': 6};
function getDayPosition(day) {
    return days[day];
}
console.log(getDayPosition('Monday'));
JakeBoggs
  • 274
  • 4
  • 17