Home > Back-end >  Return every matched day of week from array of day number in JS
Return every matched day of week from array of day number in JS

Time:09-15

I need to return a string of all matched days in a function, but Im not understanding a basic principle that I need to do this correctly. I want to map the day number to a day IE "0" = "Monday" (in this case just M-F); I believe .map is what I want, but I don't understand it enough.

function dayOfWeek(dayIndex) {
    return ["Monday","Tuesday","Wednesday","Thursday","Friday"][dayIndex] || '';
}
const days = [1,2,3,4,5];
console.log(dayOfWeek(days));

returns only "Monday", the first day. I would like it to return "Monday, Tuesday, Wednesday, Thursday, Friday"

CodePudding user response:

You can create an object defining a string value for each day of the week number. Next, you need to iterate through the array and convert numeric values to string values.

function dayOfWeek(dayIndex) {
  const days = {
    1: "Monday",
    2: "Tuesday",
    3: "Wednesday",
    4: "Thursday",
    5: "Friday",
    6: "Saturday",
    7: "Sunday"
  };
  return dayIndex.map((number) => days[number]);
}

If you want to use an array solution instead of an object, then you will need to subtract 1 from the number (since array indexes start with 0, and your days of the week start with 1)

function dayOfWeek(dayIndex) {
  const days = [
    "Monday",
    "Tuesday",
    "Wednesday",
    "Thursday",
    "Friday",
    "Saturday",
    "Sunday"
  ];
  return dayIndex.map((number) => days[number - 1]);
}
  • Related